【问题标题】:Argument of type 'Subscription' is not assignable to parameter of type 'string'. Angular“订阅”类型的参数不能分配给“字符串”类型的参数。角
【发布时间】:2020-10-19 16:26:09
【问题描述】:

这是我的订阅变量,它从配置设置中获取 api

public ChannelsAPI=this._configservice.getConfiguration("ChannelAPI").subscribe((result) => console.log(result));

这是我的 _Configservice.getConfiguration 方法

  getConfiguration(key) {
    return this._http.get('./assets/config/' + this._env + '.json').map(res => {
        this.result = res.json();
        return this.result[key];
    });
}

这是我收到错误的地方
this.ChannelsApi 可疑字符串,但它正在获得订阅,这就是我收到错误的原因

  getChannels(): Observable<Channeldata[]> {
    return this.httpClient.get<Channeldata[]>(this.ChannelsAPI)      >>>>  *ERROR PLACE*
    .pipe(
      catchError(this.errorHandler)
    )
  }

【问题讨论】:

标签: angular


【解决方案1】:

httpClient get 方法接受一个字符串,getConfiguration 返回一个可能是字符串的 observable。目前,您实际上将 channelsApi 设置为订阅的结果,因此您收到错误无法将订阅分配给字符串。为了解决这个问题,您可以通过两种方式在订阅中设置 channelsApi,以便

this._configservice.getConfiguration("ChannelAPI")
.subscribe((result) => this.channelsApi = result);

如果您愿意多次执行该步骤,也可以在获取频道中执行切换映射。

getChannels(): Observable<Channeldata[]> {
    return this._configservice.getConfiguration("ChannelAPI")
    .pipe(
      switchMap((r) => this.httpClient.get<Channeldata[]>(r))
      catchError(this.errorHandler)
    )
  }

【讨论】:

    【解决方案2】:

    您需要将this.httpClient.get&lt;Channeldata[]&gt;(this.ChannelsAPI) 替换为this.ChannelsAPI,因为您已经在此变量中准备了整个请求。 HttpClient 中的 get 方法需要传递一个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2021-10-21
      • 2021-10-13
      • 2021-09-30
      • 2018-06-24
      • 1970-01-01
      相关资源
      最近更新 更多