【发布时间】:2017-06-02 06:07:28
【问题描述】:
除了在 ngOnDestroy 中取消订阅之外,有没有办法避免对组件中的 behaviorSubject 重复订阅?到目前为止,这是我发现在我在可观察对象上创建订阅的组件上来回导航时避免重复订阅的唯一方法。
例子:
用户服务
@Injectable()
export class UserService {
constructor(private http: Http) {
this.setCurrentUser();
}
private currentUser$ = new BehaviorSubject<User>(null);
public getCurrentUser(): Observable<User> {
return this.currentUser$.asObservable();
}
public setCurrentUser(): void {
this.getLoggedUser(); //
}
private getLoggedUser(): void {
let getCurrentUserUrl = 'http://127.0.0.1:8000/users/current/'
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({
headers: headers
});
options.withCredentials = true;
this.http.get(getCurrentUserUrl, options)
.map(this.toUser)
.catch(this.handleError)
.subscribe(
user => this.currentUser$.next(user),
error => console.log("Error subscribing to currentUser: " + error)
);
}
private toUser(res: Response): User {
let body = res.json();
return body || { };
}
}
还有一个组件从用户服务订阅 observable...
export class AppComponent implements OnInit, OnDestroy {
currentUserSubscription:any;
constructor(
private userService:UserService,
private authentificationService:AuthenticationService
) {}
user:User;
ngOnInit() {
this.currentUserSubscription = this.userService.getCurrentUser().subscribe(
data => {
this.user = data;
console.log('Main : ', this.user);
}
);
}
ngOnDestroy() {
// I want to avoid writing this for every subscription
this.currentUserSubscription.unsubscribe();
}
}
如果我多次导航到组件,它会被多次创建和销毁。订阅是每次在组件初始化时创建的,并且必须与组件一起销毁。如果没有,会在下次组件初始化时重复...
有没有办法避免在 ngOnDestroy 中清理订阅?
【问题讨论】:
标签: angular observable