简体   繁体   中英

Object users in Observable Angular 8

I created a service and I try call API method (HTTP GET) and I put my data in Observable, I don't understand why I don't see all data(object) from API GET.

angular-component.ts

public allUsers$: Observable<User[]>;
constructor(private usersService: UsersService) { }
ngOnInit() {
   this.allUsers$ = this.getAllUsers();
   console.log(this.allUsers$) 
}
private getAllUsers(): Observable<User[]> {
   return this.usersService.getUsers(); 
}

In console I have this message:

在此处输入图片说明

users.service.ts

public getUsers(): Observable<User[]> {
  return this.apiService.get(this.type) as Observable<User[]>;
}

api.service.ts

public get(url: string): Observable<any> {
   return this.http.get(environment.apiUrl + `/${url}`);
}

nodejs-route.js

app.get("/", async (req, res) => {
  const getAllUsers = await User.find().populate("orders.order_id");
  res.status(200).send(getAllUsers);
});

Always keep in mind that an Observable does nothing.

As the lead RxJS developer, Ben Lesh, once said:

Observables themselves are enert. They don't stream anything or do anything. They are templates for streaming/actions/observations that will be set up on a subscription.

And there are two basic ways to subscribe:

  1. With an async pipe.
  2. Using the subscribe method.

The async pipe in a template AUTOMATICALLY subscribes and unsubscribes for you.

So in your template , you'd have something like this:

<div class="card"
     *ngIf="allUsers$ | async as users">

Then you will be able to access users in your template, such as in an *ngFor .

However, using an async pipe makes it a bit more difficult to access the data in your component code. So you can NOT just do this to see your data:

console.log(this.allUsers$) 

All that will give you is information on the Observable, as you saw.


The other option is to subscribe in your component:

sub: Subscription
users: User[]

ngOnInit() {
   this.sub = this.getAllUsers().subscribe(
    users => {
       this.users = users;
       console.log(users);
    );
}

The subscribe() method returns a Subscription that you can then use to manually unsubscribe.

You will then have an array of users User[] , NOT an Observable<User[]> as your component property. Your template can then bind to this array.

The first technique (async pipe) is normally the recommended approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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