Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When i started learning angular i readed blogs that using async pipe is better because it makes automatically unsubscribe from the data stream. So i do

HTML

<div *ngIf="users | async">
    <ul>
        <li *ngFor="let user of users | async">{{ user.name }}</li>
    </ul>
</div>

TS FILE

export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {};
  users: any;
  ngOnInit() {
   this.users = this.http.get('https://jsonplaceholder.typicode.com/userss');
   console.log(this.users);
  }
}

so in the ngOnInit method the console log

console.log(this.users);

gives me

Observable?{_isScalar: false, source: Observable, operator: MapOperator

I got the values in HTML with the async pipe, but what if i will need to do some logic in my componenet - ts file based on the users that i got from backend.

If i want the data inside i could do it with subscribe. But i don't want that because at first place i started with async pipe because i don't want to manualy unsubscribe from it.

So in this situation how can i get the value from the observable without subscribe so at the end when the component is detroyed i should not care about unsubscribing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to do some transformations inside the Observable simply use map pipe-able operator:

onlyActiveUsers: Observable<any>;

ngOnInit() {
   this.onlyActiveUsers$ = this.http
     .get('https://jsonplaceholder.typicode.com/userss')
     .pipe(
        map(users => {
           const transformedUsers = users.filter(user => user.isActive);
           return transformedUsers;
        })
     )
  }

You can use | async pipe for the variable onlyActiveUsers$ in your template.

If you want to store some values inside your component before or after the transformation, use tap:

onlyActiveUsers: Observable<any[]>;
allUsers: any[];

ngOnInit() {
   this.onlyActiveUsers$ = this.http
     .get('https://jsonplaceholder.typicode.com/userss')
     .pipe(
        tap(allUsers => this.allUsers = allUsers), // here, or after "map" below
        map(users => {
           const transformedUsers = users.filter(user => user.isActive);
           return transformedUsers;
        })
     )
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...