简体   繁体   English

如何在angular2中处理可观察类型的数据

[英]how to manipulate data of observable type in angular2

I am new angular2 so please ignore if you find it the basic question. 我是新的angular2,因此,如果您发现它是基本问题,请忽略它。

I have a variable of type Observable 我有一个Observable类型的变量

users: Observable<User[]>;

and in the constructor, I am filling it 在构造函数中,我正在填充它

constructor(private roleService: RoleService, private userService: UserService) {
        this.users = this.userService.getAllUsers();
}

Now I want to manipulate/iterate the data of this.users . 现在,我要操纵/迭代this.users的数据。 How can I do that? 我怎样才能做到这一点?

You can use map or any other of the long list of available operators. 您可以使用map或任何其他可用的运算符列表。

You need to subscribe to execute the observable, otherwise it won't do anything. 您需要订阅以执行可观察的对象,否则它不会执行任何操作。 You can also use .forEach(...) , .toArray() , (and others) instead of subscribe() : 您还可以使用.forEach(...) .toArray() (及其他)代替.forEach(...) subscribe()

constructor(private roleService: RoleService, private userService: UserService) {
        this.users = this.userService.getAllUsers()
        .map(val => val + 'xxx')
        .subscribe(val => console.log(val));
}

See also https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html 另请参阅https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

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

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