Как решать ошибки типа void 'нельзя назначить параметру типа' (значение: [Post, any, {} []]) => void ' - PullRequest
0 голосов
/ 08 июня 2019

Я постоянно получаю сообщение об ошибке при попытке извлечь что-то из Ionic из Wordpress.

[ng] ERROR in src/app/post/post.page.ts(30,37): error TS2345: Argument of type '(post: Post) => void' is not assignable to parameter of type '(value: [Post, any, {}[]]) => void'.
[ng]   Types of parameters 'post' and 'value' are incompatible.
[ng]     Type '[Post, any, {}[]]' is not assignable to type 'Post'.
[ng]       Property 'author' is missing in type '[Post, any, {}[]]'.

Это мой wordpress-restapi-service.ts файл:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, forkJoin, throwError, empty, of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class WordPressRestapiService {

  baseRestApiUrl: string = 'https://my-website-here/wp-json/wp/v2/';

  constructor(private httpClient: HttpClient) { }

  getRecentPosts(categoryId: number, page: number = 1): Observable<Post[]> {
    // Get posts by a category if a category id is passed
    let category_url = categoryId ? ("&categories=" + categoryId) : "";

    return this.httpClient.get(this.baseRestApiUrl + "posts?page=" + page + category_url).pipe(
      map((posts: Post[]) => {
        return posts.map((post) => new Post(post));
      }),
      catchError(error => {
        return Observable.throw('Something went wrong ;)');
      })
    );
  }

  getPost(postId) {
    return this.httpClient.get(this.baseRestApiUrl + "posts/" + postId).pipe(
      map((res: any) => res),
      flatMap((post: any) => {
        return forkJoin(
          of(new Post(post)),
          this.getComments(post.id),
          this.getCategories(post)
        )
      })
    );
  }

    getComments(postId: number, page: number = 1) {
    return this.httpClient.get(this.baseRestApiUrl + "comments?post=" + postId).pipe(
      map(comments => {
        let commentsArray = [];     

        Object.keys(comments).forEach(function (key) {
          commentsArray.push(new Comment(comments[key]));
        });

        return commentsArray;
      }),
      catchError(val => of(val))
    );
  }

  getCategories(post) {
    let observableBatch = [];

    post.categories.forEach(category => {
      observableBatch.push(this.getCategory(category));
    });

    return forkJoin(observableBatch);
  }

  getCategory(categoryid: number): Observable<Category> {
    return this.httpClient.get(this.baseRestApiUrl + "categories/" + categoryid).pipe(
      map(category => {
        return new Category(category);
      }),
      catchError(val => of(val))
    );
  }
}

export class Post {
  author: number;
  categories: number[];
  comment_status: string;
  content: object;
  date: string;
  date_gmt: string;
  excerpt: object;
  featured_media: number;
  format: string;
  guid: object;
  id: number;
  link: string;
  meta: object;
  modified: string;
  modified_gmt: string;
  ping_status: string;
  slug: string;
  status: string;
  sticky: boolean;
  tags: number[];
  template: string;
  title: object;
  type: string;
  _links: object;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

export class Category {
  id: number;
  count: number;
  description: string;
  link: string;
  name: string;
  slug: string;
  taxonomy: string;
  parent: number;
  meta: object;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

export class Comment {
  id: number;
  author: number;
  author_email: string;
  author_ip: string;
  author_name: string;
  author_url: string;
  author_user_agent: string;
  content: object;
  date: string;
  date_gmt: string;
  link: string;
  parent: number;
  post: number;
  status: string;
  type: string;
  author_avatar_urls: object;
  meta: object;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

А это фрагмент этой страницы, где он идет не так:

  getPost(postId) {
    return this.httpClient.get(this.baseRestApiUrl + "posts/" + postId).pipe(
      map((res: any) => res),
      flatMap((post: any) => {
        return forkJoin(
          of(new Post(post)),
          this.getComments(post.id),
          this.getCategories(post)
        )
      })
    );
  }

Я уже проверил rxjs docs , но ничего не смог найтиэто могло бы помочь мне.Я не смог найти flatMap там, поэтому я должен сделать что-то не так, но я не знаю, что ...

Редактировать: И мой post.page.ts, как и просили:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { LoadingController } from '@ionic/angular';
import { WordPressRestapiService, Post } from '../services/wordpress-restapi.service';

@Component({
  selector: 'app-post',
  templateUrl: './post.page.html',
  styleUrls: ['./post.page.scss'],
})
export class PostPage implements OnInit {

  id: string;
  private post: Post = new Post;

  constructor(
    public loadingController: LoadingController, 
    private route: ActivatedRoute, 
    private wordpressService: WordPressRestapiService) {}

  async ngOnInit() {

    const loading = await this.loadingController.create();
    await loading.present();

    this.id = this.route.snapshot.paramMap.get('id');

    this.getPost(this.id).subscribe((post: Post) => {
      this.post = post;
      loading.dismiss();
    });
  }

  getPost(postId) {
    return this.wordpressService.getPost(postId);
  }
}

1 Ответ

0 голосов
/ 08 июня 2019

Проблема в следующем коде в вашем post.page.ts -

this.getPost(this.id).subscribe((post: Post) => {
      this.post = post;
      loading.dismiss();
    });

Здесь вы пытаетесь присвоить наблюдаемому ответу "this.getPost" значение this.post.Ответ «this.getPost» не относится к типу "Post" [это массив;это то, что упоминается об ошибке компиляции: тип «[Post, any, {} []]» не может быть назначен типу «Post».].

Вы можете изменить ваш getPost вашего сервиса на проект forkJoinвыведите на "Post" вот так [оператор карты уведомлений после forkjoin] -

getPost(postId) {
    return this.httpClient.get(this.baseRestApiUrl + "posts/" + postId).pipe(
      map((res: any) => res),
      mergeMap((post: any) => {
        return forkJoin(
          of(new Post(post)),
          this.getComments(post.id),
          this.getCategories(post)
        ).pipe(
          map((joined) => joined[0])
        )
      })
    );
  }

ИЛИ обновите свой код в post.page.ts вот так -

this.getPost(this.id)
    .pipe(map(v) => v[0])
    .subscribe((post: Post) => {
      this.post = post;
      loading.dismiss();
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...