加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – Subscription’不能分配给类型

发布时间:2020-12-17 17:29:16 所属栏目:安全 来源:网络整理
导读:我在获取服务以在页面上显示结果时遇到问题.错误是订阅方法返回订阅类型,我不知道试图将它带到产品数组.产品位于json文件中. 建立: 我正在尝试通过阅读教程来学习Angular 2.教程已过时,我正在使用最新版本的angular(ng -v = @ angular / cli:1.4.2).我使用
我在获取服务以在页面上显示结果时遇到问题.错误是订阅方法返回订阅类型,我不知道试图将它带到产品数组.产品位于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);
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读