【发布时间】:2019-05-17 23:05:16
【问题描述】:
所以我在 Angular 中开发一个新组件,在 ngOninit 中我有以下异步函数...
This.getUserProfile 需要在我调用 this.getPrivateGroup() 之前完成,并且 this.getPrivateGroup() 需要在我调用 this.loadGroupPosts() 之前完成。我知道我可以在异步请求的回调中编写这些函数,但我想知道是否有办法将其保留在 ngOnInit 中以使其更清洁?
有人有想法吗?
ngOnInit() {
this.getUserProfile();
// my-workplace depends on a private group and we need to fetch that group and edit
// the group data before we proceed and get the group post
if (this.isItMyWorkplace) {
this.getPrivateGroup();
}
this.loadGroupPosts();
}
getUserProfile() {
this._userService.getUser()
.subscribe((res) => {
this.user = res.user;
console.log('log user', this.user);
this.profileImage = res.user['profile_pic'];
this.profileImage = this.BASE_URL + `/uploads/${this.profileImage}`;
}, (err) => {
this.alert.class = 'alert alert-danger';
if (err.status === 401) {
this.alert.message = err.error.message;
setTimeout(() => {
localStorage.clear();
this._router.navigate(['']);
}, 3000);
} else if (err.status) {
this.alert.class = err.error.message;
} else {
this.alert.message = 'Error! either server is down or no internet connection';
}
});
}
getPrivateGroup() {
console.log('user check', this.user);
this.groupService.getPrivateGroup(`${this.user.first_name}${this.user.last_name}`)
.subscribe((group) => {
console.log('received response', group)
})
}
// !--LOAD ALL THE GROUP POSTS ON INIT--! //
loadGroupPosts() {
this.isLoading$.next(true);
this.postService.getGroupPosts(this.group_id)
.subscribe((res) => {
// console.log('Group posts:', res);
this.posts = res['posts'];
console.log('Group posts:', this.posts);
this.isLoading$.next(false);
this.show_new_posts_badge = 0;
}, (err) => {
swal("Error!", "Error while retrieving the posts " + err, "danger");
});
}
// !--LOAD ALL THE GROUP POSTS ON INIT--! //
【问题讨论】:
-
贴出各个函数的代码
-
getPrivateGroup函数长什么样子? -
好的,我发一下
-
新增功能。
-
除非你用 @ 提醒他们,否则他们不会收到通知
标签: javascript angular asynchronous