简体   繁体   English

如何使用 httpClient 从 angular 中的 observables 访问数据?

[英]How to access data from observables in angular using httpClient?

I'm trying to connect to API with my angular app and I want to create a get function that returns an array.我正在尝试使用我的 angular 应用程序连接到 API,并且我想创建一个返回数组的 get function。 Connecting works fine, but the function doesn't return what I want.连接工作正常,但 function 没有返回我想要的。

Here's code.这是代码。

export class ApiService {
  constructor(private http: HttpClient) {}

  public getUsers() {
    const res = this.http.get('http://localhost:3000/user');
    res.subscribe(response => {
      console.log(response);
      return response;
    });
  }
}

console.log() prints an array, but when I try to do users = this.getUsers(); console.log() 打印一个数组,但是当我尝试执行users = this.getUsers(); and console.log() it, it prints ZoneAwarePromise instead.和 console.log() 它,它会打印 ZoneAwarePromise 。

ZoneAwarePromise ZoneAwarePromise

You need to return the obserable and await it in your component, here is an example:您需要返回 obserable 并在组件中等待它,这是一个示例:

Service服务

GetUser(): Observable<UserObject> {
    return this.http.get<UserObject>(url) 
}

And in your component you can await by doing the following:在您的组件中,您可以通过执行以下操作来等待:

getUserInfo() {
    this.dataService.GetUser().subscribe(response => {
      console.log(response);
    }, error => {
      console.log(error);
    });
}

HttpClient.get returns an Observable, that's why you need to subscribe to get its content. HttpClient.get返回一个 Observable,这就是为什么你需要订阅来获取它的内容。 So, this assign you're trying to do is not correct, your method does not return the array you want.因此,您尝试执行的此分配不正确,您的方法不会返回您想要的数组。

A common way to to this, considering that this.users is at component level would be:考虑到this.users处于组件级别,一种常见的方法是:

.service

getUsers(): Observable<User[]> {
  return this.http.get('http://localhost:3000/user');
}

.component

users: User[];

ngOnInit {
  this.service.getUsers()
    .subscribe(users => this.users = users);
}

Please try below.请在下面尝试。 It should work fine它应该可以正常工作

export class ApiService {
  constructor(private http: HttpClient) {}

  public getUsers() {
    const res = this.http.get('http://localhost:3000/user').subscribe(response => {
      console.log(response);
      return response;
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM