Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

angular - How can i get values from observable without using subscribe

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

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

1 Reply

0 votes
by (71.8m points)

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;
        })
     )
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...