Аргумент типа X не может быть назначен параметру ошибки типа X в Angular 7 - PullRequest
0 голосов
/ 02 января 2019

У меня есть две модели с именами «UserBook» и «Comment».

Book Model: book_comments - это массив типа Comment

export class UserBook {
    id: number;
    book_name: string;
    book_comments: Array<Comment[]>;

    constructor(book) {
        this.id = book.id ? book.id : null;
        this.book_name = book.name ? book.name : null;
        this.book_comments = [];
    }
}

Comment Model:

export class Comment {
    id: number;
    comment: string;
    date: string;

    constructor(comment) {
        this.id = comment.id ? comment.id : null;
        this.comment = comment.comment ? comment.comment : null;
        this.date = comment.date ? comment.date : null;
    }
}

Я хочу создать новый комментарий и вставить его в массив комментариев UserBook

book: UserBook;

postNewComment(comment): any {

    return this.http.post(environment.api + '/book/comments', {comment: comment}).pipe(
        tap(
            (response) => {
                this.book.book_comments.unshift(new Comment(response['comment']));
            },
            (error) => {
                console.log(error);
            }
        )
    );

}

Но я вижу эту ошибку.

"Ошибка: аргумент типа Comment не назначается параметрутипа Comment "

Если я изменю тип book_comments на" any ", тогда он работает.

Но я не мог понять, почему он не принимает тип Comment [].Может ли кто-нибудь помочь мне об этом.

1 Ответ

0 голосов
/ 02 января 2019

Вот одно из возможных решений. Вы объявили массив T, где T также является массивом. Так что либо отмените смещение в массиве Comment [], либо попробуйте то, что я сделал ниже, упростили без внутреннего вызова.

import { Component, OnChanges, OnInit } from '@angular/core';

    class UserBook {
      id: number;
      book_name: string;
      book_comments: Array<Comment> = [];

      constructor(book) {
        this.id = book.id ? book.id : null;
        this.book_name = book.name ? book.name : null;
      }
    }

    class Comment {
      id: number;
      comment: string;
      date: string;

      constructor(comment) {
        this.id = comment.id ? comment.id : null;
        this.comment = comment.comment ? comment.comment : null;
        this.date = comment.date ? comment.date : null;
      }
    }

    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
    })
    export class HomeComponent implements OnInit {

      book: UserBook;

      public ngOnInit(): void {
        this.book = new UserBook({ id: 123, name: 'My Book' });
        this.book.book_comments.unshift(new Comment({ id: 1, comment: 'Hello World' }));
      }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...