【问题标题】:Get result object as undifine when getting data from web api. only in first call从 web api 获取数据时获取未定义的结果对象。仅在第一次通话中
【发布时间】:2019-05-21 17:39:34
【问题描述】:

尝试从 Web Api 获取数据数组。当我第一次调用 api 时,结果返回指示未定义。之后的任何调用都会按预期获得结果。

Oncall 方法将结果存储到工作站

@Injectable()
export class StationService {

    private stations;
    constructor(private webservice: WebService) { }

    Oncall() {
        this.webservice.GetData('Search/GetStations').subscribe((respons: Station[]) => { this.stations = respons; });
        console.log(this.stations);
        console.log('----------------------------------');
    }
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Station } from '../dataModels/stationModel';
import { map } from 'rxjs/operators';

@Injectable()
export class WebService {
    private url = 'http://localhost:11835/Api/';

    constructor(private http: HttpClient) { }

    GetData(path: string) {
        return this.http.get<Station[]>((this.url + path)).pipe(
            map((data: Station[]) => data)
        );
    }
}

谢谢

【问题讨论】:

    标签: angular get


    【解决方案1】:

    更改您的代码:

        Oncall() {
            this.webservice.GetData('Search/GetStations').subscribe((respons: Station[]) => { 
             this.stations = respons;
             console.log(this.stations);
             console.log('----------------------------------');
            });
    
        }
    

    问题是第一次调用服务函数(GetData)需要一段时间来获取数据,而你正在运行console.log(this.stations);后。您的那部分代码异步运行,不会等待分配完成 this.stations = respons;

    下次调用它会显示以前的值

    【讨论】:

      【解决方案2】:

      您的控制台日志超出了分配范围。在数据有机会返回之前,您正在尝试记录您看到的未定义对象。当您第二次点击它时,数据已从第一次调用中检索到,这就是它记录的原因,但如果您对其进行了任何更改,您可能会注意到数据已过时。

      如果您想在最初获取数据后查看 console.log,请将控制台日志添加到将数据分配给对象的位置,如下所示。

      Oncall() {
              this.webservice.GetData('Search/GetStations').subscribe((respons: Station[]) => { 
               this.stations = respons;
               console.log(this.stations);
              });
          }
      

      【讨论】:

        【解决方案3】:

        您的 console.log 代码是同步发生的,因为它超出了订阅函数的范围,所以它返回未定义。然而,在那之后,异步代码立即解析并将“this.stations”设置为响应。因此,您总是在查看一个 Web 请求后面的结果。

        Leonardo 建议的更改将导致在 http 请求解析后出现日志

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-23
          • 2023-04-07
          • 2021-04-26
          • 1970-01-01
          • 2019-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多