订阅'不能分配给类型

时间:2017-09-24 14:57:32

标签: angular observable

我在获取服务以在页面上显示结果时遇到问题。错误是订阅方法返回订阅类型,我不知道试图将它带到产品数组。产品位于json文件中。

设定: 我正在尝试通过阅读教程来学习Angular 2。教程已过时,我正在使用最新版本的angular(ng -v = @ angular / cli:1.4.2)。我使用ng new和ng generate来设置app。

产品list.component.ts

export class ProductListComponent implements OnInit {

  pageTitle = 'Product List';
  imageWidth = 50;
  imageMargin = 2;
  showImage = false;
  listFilter = '';
  products: IProductList[];
  subscription: Subscription;
  errorMessage = '';

  constructor(private _productListService: ProductListService) {
  }

  ngOnInit() {
**// ERROR - 'Subscription' is not assignable to type 'IProductList[]'**
    this.products = this._productListService.getProducts()  // ******** ERROR ******
      .subscribe(
        products => this.products = products,
        error => this.errorMessage = <any>error);
  }

产品list.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { IProductList } from './product-list';


@Injectable()
export class ProductListService {
  private _productListUrl = 'api/product-list/product-list.json';

  constructor(private _http: Http) { }

  getProducts(): Observable<IProductList[]> {
    return this._http.get(this._productListUrl)
            .map((response: Response) => <IProductList[]>response.json())
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server Error');
  }
}

产品list.component.html

    <tr *ngFor='let product of products | async | productFilter: listFilter' >
      <td>
        <img *ngIf='showImage' [src]='product.imageUrl' [title]='product.productName' [style.width.px]='imageWidth' [style.marging.px]='imageMargin'>
      </td>
      <td>{{product.productName}}</td>
      <td>{{product.productCode | lowercase }}</td>
      <td>{{product.releaseDate}}</td>
      <td>{{product.price | currency:'USD':true:'1.2-2' }}</td>
      <td><app-ai-star [rating] = 'product.starRating'
           (ratingClicked)='onRatingClicked($event)'></app-ai-star></td>
    </tr>

2 个答案:

答案 0 :(得分:5)

问题是您要将订阅设为= getProducts()来电。

ngOnInit() {
    this.subscription = this._productListService.getProducts() // subscription created here
      .subscribe(
        products => this.products = products, // value applied to products here
        error => this.errorMessage = <any>error);
  }

答案 1 :(得分:0)

this.products中分配subscribe()的值。您可以忽略返回的订阅对象,如下面的代码段所示。

ngOnInit() {
    this._productListService.getProducts() 
      .subscribe(
        products => this.products = products,
        error => this.errorMessage = <any>error);
  }