【问题标题】:Web API not being called from angular未从角度调用 Web API
【发布时间】:2021-11-06 19:52:26
【问题描述】:

我正在尝试以角度调用自定义 API,但由于某种原因它没有调用它。在此之前,我在 Angular 中(在 _api.service.ts 中)制作了 10 个以相同方式调用 Web API 的函数,它们是正确的,我的 Web API 被调用并返回数据,一切都很好。然后我在 web API 中又创建了一个方法,在 angular 中又创建了一个组件(其中调用了函数 getList()),但它不起作用,从未调用过 API。

getList(id: string, chosen: string): Observable<StopListModel[]> {
        let myUrl: string = API_URL + '/stop/list';
        myUrl += '/' + id;
        myUrl += '/' + chosen;
        //debugger goes to this line, url is correct but API not called
        return this.http.get<StopListModel[]>(myUrl, this.httpUtils.getHTTPHeader());
   }

当我调试时,我看到 API 的 url 是从 angular 正确发送的,就像在我的项目中成功调用 API 的其他 10 个函数一样,所以我认为我不需要从我的 Web API 向您发送代码。我很困惑,所以我将调用 getList() 的行从新组件移动到现有组件,我已经知道我的 _api.service 将成功调用 Web API,因为在该组件中有一个函数(例如 getUsers() )正确调用 API。而且它没有用,getList() 没有调用 API。

我认为 getList() 的 Web API 有问题,但为了确保在第二个组件中我调用了另一个 _api.service 函数(从另一个组件调用时有效),令人惊讶的是 - 没有调用 API也适用于该功能。

然后我看到了我认为的问题是:当我尝试在我的 any 组件中调用 any 函数时,所有这些“新”函数都不会调用 API,只是已经存在的旧的,即使它们在自己的组件中正常工作。

export class DetaljiStopoviComponent{
            stops$: Observable<StopStatisticsModel[]>;
            list$: Observable<StopListModel[]>
            constructor(
              private apiService: APIService,
              route: ActivatedRoute
            ) {
                var id = route.snapshot.params['id'];
                this.stops$ = this.apiService.getStopStatistics(id); //this works, it was there before - but any other calling I add under this, API is not called (this is the case for every component, every function)
                this.list$ = this.apiService.getList(id, '3'); //this is the newest one, I can't make it call API even in the empty components      
            }
}

我很困惑,没有经验,我很想知道问题出在哪里。我认为 Web API 没有问题,但我不确定。有人有建议吗?

【问题讨论】:

  • 在组件中,您正在调用apiService.getStopList,但您附加了getList() 代码。方法一样吗?
  • 抱歉,在编辑代码发布到这里时(所以名称更容易理解),我不小心留下了“停止”。这个方法一样,忽略这个Stop
  • 如果您在getList 中放置一个调试器,它会被调用吗?您是否看到对您要请求的 URL 的调用?
  • 是的,调试器一路返回 this.http.get..... 并且 url 是正确的。我知道 url 是正确的,因为当我把它放在邮递员中时,我会得到正确的结果

标签: javascript angular observable


【解决方案1】:

我认为这是语法问题,对于 get 方法试试这个

return this.http.get<StopListModel[]>(myUrl, {headers:this.httpUtils.getHTTPHeader()});

【讨论】:

    【解决方案2】:

    您好像忘记订阅了:

    this.stops$ = this.apiService.getStopStatistics(id);
    this.list$ = this.apiService.getList(id, '3');   
    

    我认为 this.stops$ 适合你,因为在模板的某个地方你有异步管道(stops$ | async)。

    所以尝试这样做:

    this.list$.subscribe(response => console.log(response));
    

    在该请求应该发送之后

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 2020-06-08
      • 2017-06-04
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多