如何写一个可观察的

时间:2019-05-11 16:37:28

标签: angular

在编写第一个可观察的get函数时,我遇到语法错误,在下面的代码中,我的库存组件未将“类型'Cagr []'分配给类型'可观察”:

export class StocksComponent {

stock: String;
public buySellData$: Observable<Cagr[]>

constructor(private api: ApiService){}

get(stock) {
  //make sure to subscribe to get the data
  this.api.getStock(stock).subscribe(data => { console.log("data from backend", data);
  this.buySellData$ = data;  // SYNTAX ERROR ON THIS LINE
  });
 }

}

这是服务ts:

export class ApiService {

  apiURL = environment.apiUrl;
  stockUrl = this.apiURL + '/api/stock';

  Icagr$: Observable<Cagr[]>


  constructor(private http: HttpClient) { }
  // getStock returns an Observable<Cagr[]>
  public getStock(name: string) : Observable<Cagr[]>{
   // url should be api/stock/aapl
    const url = `${this.apiURL}/api/stock/${name}`;
    console.log('url', url)
   return this.Icagr$ = this.http.get<Cagr[]>(url); 
  }

我希望这两种类型都是可观察的,但实际上是Carg []

1 个答案:

答案 0 :(得分:1)

您的问题是您正在进行订阅并将可观察的内容展开为具体类型。

  

this.api.getStock(stock).subscribe。

如果您不需要链中的内容,只需将您的声明从“可观察的”从公开的buySellData $:可观察的更改为公共的 buySellData:Cagr []