【问题标题】:How to set correct type on Observables?如何在 Observables 上设置正确的类型?
【发布时间】:2017-03-12 23:39:03
【问题描述】:

observables/angular 2 的新手。在我的组件上正确更新了内容,但我从 typescript 收到此错误:

“StoreItem[]”类型的参数不能分配给类型参数 '字符串'。

有人可以指导我如何设置正确的类型吗?

//store.item.interface.ts
  export interface StoreItem {
  id?: number;
  qty?: number;
  nameList?:Array<string>;
  title: string;
  price: number;
}


//cart.service.ts

import {Injectable} from '@angular/core'
import {Subject}    from 'rxjs/Subject';
import { StoreItem } from '../store.item.interface'

@Injectable()
export class CartService {
  private _subject = new Subject<string>();
  private _cartList:StoreItem[] = [];

  cartList$ = this._subject.asObservable();


  addItem(item:StoreItem){
    this._cartList.push(item)
    this._subject.next(this._cartList)

  }
}

【问题讨论】:

    标签: angularjs typescript rxjs


    【解决方案1】:

    只需为 Subject 设置正确的类型(假设您要发出整个 _cartList 数组):

    private _subject = new Subject<StoreItem[]>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-19
      • 2017-05-26
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多