首页 > 解决方案 > 如何解决像 void' 这样的错误不能分配给类型为 '(value: [Post, any, {}[]]) => void' 的参数

问题描述

在尝试IonicWordpress.

[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 文档,但找不到任何可以帮助我的东西。我找不到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);
  }
}

标签: angularwordpressionic-frameworkrxjsionic4

解决方案


The problem is in the following code in your post.page.ts -

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

Here you are trying to assign the response of "this.getPost" observable to this.post. The response of "this.getPost" is not of type "Post" [it is an array; this is what compile error is mentioning - Type '[Post, any, {}[]]' is not assignable to type 'Post'.].

You can either change your getPost of your service to project forkJoin output to "Post" like this [notice map operator after 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])
        )
      })
    );
  }

OR update your code in post.page.ts like this -

this.getPost(this.id)
    .pipe(map(v) => v[0])
    .subscribe((post: Post) => {
      this.post = post;
      loading.dismiss();
    });

推荐阅读