【问题标题】:How to route ASP.Net Core api return value to appropriate observable based on data type returned如何根据返回的数据类型将 ASP.Net Core api 返回值路由到适当的 observable
【发布时间】:2019-05-31 21:02:58
【问题描述】:

我创建了一个带有 Angular 7 前端的 ASP.NET Core Web Api 后端。 Api 中的一种方法可以将对象或数组返回给 Angular 服务。如何根据返回的数据类型路由到特定的 observable?我是 Angular 的菜鸟,因此我们将不胜感激。

Angular service call to Api:

getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data =>
    this.apiData.next(data)
    );
  }


Portion of Web Api that returns array if more than one APN present:

// if more than one item in list, get status information for each and return list to user to select appropriate apn
            if (propApn.Count > 1)
            {
                return Ok(propApn);               
            }


Portion of same method to return object if only one value for APN:

var resultsModel = new Results
            {
                ArcGisLink = arcGisLink,
                HistInfoLink = histInfoLink,
                PropInfoLink = propInfoLink          
            };

            return Ok(resultsModel);

【问题讨论】:

    标签: rxjs angular7 asp.net-core-webapi


    【解决方案1】:

    你不能这样做。 Typescript 只能在构建时基于静态分析键入内容,您的描述需要 Typescript 在构建时知道您的 API 调用的结果,而它不会这样做。

    您可以做的最好的事情是表明您的 API 调用可以返回您的两者:

    public myApiFunc(req: MyRequestModel): Observable<any>
    

    但这仍然需要您弄清楚在运行时返回的类型。

    【讨论】:

      【解决方案2】:

      我找到了一个可行的解决方案...

      getLinksFromSitus(situs: any) {
          this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data => {
          if (data.hasOwnProperty('arcGisLink')) {
            this.apiData.next(data);
          } else {
            let vals = [];
            vals = this.apiPropApn.getValue();
            const item = vals.concat(data);
            this.apiPropApn.next(item);
            }
          });
        }
      

      因此,订阅 HttpResponse 后,我可以检查响应中的数据是否包含已知属性。如果它不包含已知属性,则它将数据连接到 BehaviorSubject 数组。效果很好。

      【讨论】:

        猜你喜欢
        • 2021-02-01
        • 2019-12-14
        • 2018-04-10
        • 2020-10-22
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多