-2

我正在尝试以 userId 作为参数发出 HTTP 获取请求,并使用 Angular 返回单个用户配置文件,但不断返回未定义的数据。我知道问题不在于我的后端服务器,因为 Postman 的相同 HTTP 获取请求 可以正常工作。 此外,我从我的 Angular HTTP 请求中得到了 这个异常 (后端是用 Java 编写的),但不是来自 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不正确。有人知道我在做什么错吗?

编辑:这是 来自浏览器控制台的错误截图。不确定它是否相关。

4

2 回答 2

2

该调用this.profileService.getProfile()返回一个 Observable,即async. 所以调用流程是这样做的:

  • this.profileService.getProfile("5e7bd87e05854a05cc0f6898")启动 HTTP 请求
  • console.log(this.profile)被调用(这是undefined因为它还没有被设置)
  • 未来某个时间: HTTP 请求完成
  • 那么,你的回调函数在你的.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 Socket 或其他东西有关。只是大胆猜测,但我怀疑您获取用户配置文件的 HTTP 调用会导致该错误。

于 2020-04-02T21:08:17.600 回答
1

HTTP 请求是异步解析的,因此当您打印 console.log( this.profile );GET 请求时仍未解析,因此分配给的值this.profile仍未定义。如果您想查看值,只需在console.log( this.profile );执行分配后将其放入 subscribe 即可profile => this.profile = profile,

于 2020-04-02T20:55:02.433 回答