angular – Subscription’不能分配给类型

前端之家收集整理的这篇文章主要介绍了angular – Subscription’不能分配给类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在获取服务以在页面显示结果时遇到问题.错误订阅方法返回订阅类型,我不知道试图将它带到产品数组.产品位于json文件中.

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

产品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>

解决方法

问题是你想让你的订阅= 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);
  }

猜你在找的Angularjs相关文章