如何解决在管道或订阅中设置组件属性
说我有一个组件,我调用我的api服务以返回User[]
类型的可观察对象,仅发出一个值。设置全局变量首选哪种方式?
注意:在此示例中,我不在html文件中使用异步管道
使用Subscribe and takeUntil
export class ExampleComponent implements OnInit,OnDestroy {
users: User[];
ngUnsubscribe: Subject<unknown> = new Subject<unknown>();
constructor(
private userService: UserService
) { }
ngOnInit() {
this.userService.getUsers()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(res => this.users = res);
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
使用带有空订阅的管道运算符
export class ExampleComponent implements OnInit {
users: User[];
constructor(
private userService: UserService
) { }
ngOnInit() {
this.userService.getUsers()
.pipe(map(users => this.users = users))
.subscribe();
}
}
解决方法
this.userService
.getUser()
.pipe(take(1))
.subscribe((user) => {
this.userList = user;
});
或者您可以像这样在HTML的异步管道中使用
user$|async
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。