Angular HTTP get请求返回未定义

时间:2020-04-02 20:09:36

标签: javascript angular typescript http http-parameters

我正在尝试使用userId作为参数来发出HTTP get请求,并使用Angular返回单个用户配置文件,但始终获取返回的未定义数据。我知道问题不在我的后端服务器上,因为与邮递员使用相同的HTTP获取请求 works correctly. 另外,我正在 this exception (后端是用Java编写的)来自我的Angular HTTP请求,而不是来自Postman HTTP请求。

profile.component.ts:

profile: Profile;
constructor(private profileService: ProfileService) {
}
ngOnInit() {
  this.getProfile();
}
getProfile() {
  this.profileService.getProfile("5e7bd87e05854a05cc0f6898").subscribe(
    profile => this.profile = profile,
  );
  console.log( this.profile );
}

profile.service.ts:

getProfile(userId: string) {
    let params = new HttpParams().set("id", userId);
    console.log( "executing HTTP get" );

    //return this.httpClient.get<any>( "http://localhost:8080/user", { params: params });
    // I've tried this above method and the one below

    return this.httpClient.get("http://localhost:8080/user", { params: params })
    .pipe(
      map((data: any) => {
        const profile: Profile = new Profile( data.object.id,
                               data.object.username,
                               data.object.password,
                               data.object.fname,
                               data.object.lname,
                               data.object.email,
                               data.object.joined );
        return profile;
      })
    );
   }

console.log( this.profile )在浏览器控制台中以undefined的形式出现。我认为我使用的是subscribe错误。有人知道我在做什么错吗?

编辑:这是屏幕截图 error 从浏览器控制台。不确定是否相关。

2 个答案:

答案 0 :(得分:2)

调用this.profileService.getProfile()返回一个async的Observable。因此,呼叫流程就是这样做的:

  • this.profileService.getProfile("5e7bd87e05854a05cc0f6898")启动HTTP请求
  • console.log(this.profile)被调用(它是undefined,因为尚未设置)
  • 将来的某个时间: HTTP请求完成
  • THEN ,您的.subscribe()中的回调函数将运行。 (在您的情况下,profile => this.profile = profile,

要解决您的问题,只需将console.log移至.subscribe()回调中即可。

getProfile() {
  this.profileService.getProfile("5e7bd87e05854a05cc0f6898").subscribe(profile => {
    this.profile = profile;
    console.log( this.profile );
  });
}

我不确定该错误的相关原因,因为您尚未发布notifications.service.ts代码。这可能与您如何设置个人资料有关, 但我不能不看其他代码就知道。与Java错误相同。不确定Postman请求和Angular请求之间有什么区别。

修复console.log将解决您的undefined错误。希望这将帮助您找出Java错误。 该Java错误似乎与Web套接字有关。只是一个疯狂的猜测, 但我怀疑您用于获取用户个人资料的HTTP调用会导致该错误。

答案 1 :(得分:1)

HTTP请求是异步解析的,因此当您打印console.log( this.profile );时,GET请求仍然无法解析,因此分配给this.profile的值仍未定义。如果要查看该值,则在执行console.log( this.profile );设置后将profile => this.profile = profile,放入订阅中。