F. *_*ron 4 observable angular
除了在 ngOnDestroy 中取消订阅之外,是否有办法避免对组件中的 BehaviourSubject 进行重复订阅?到目前为止,这是我发现在在可观察对象上创建订阅的组件上来回导航时避免重复订阅的唯一方法。
例子:
一项用户服务
@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 || { };
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个从用户服务订阅可观察的组件......
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我多次导航到该组件,它就会被多次创建和销毁。每次组件初始化时都会创建订阅,并且必须随组件一起销毁。如果没有,它将在下一个组件初始化时重复......
有没有办法避免在 ngOnDestroy 中清理订阅?
如果您只想订阅一次,则需要在模板上使用异步管道,异步管道将自动管理取消订阅。如果您喜欢这种方法,您需要使用智能组件和演示组件来编写应用程序。检查这个答案
取消订阅的另一种方法是创建一个主题,这样订阅就会完成,直到主题发出一个值。您应该始终取消订阅,否则会出现内存泄漏。
export class AppComponent implements OnInit, OnDestroy {
currentUserSubscription:any;
constructor(
private userService:UserService,
private authentificationService:AuthenticationService,
private _destroy : Subject() = new Subject();
) {}
user:User;
ngOnInit() {
this.currentUserSubscription = this.userService.getCurrentUser()
.takeUntil(this._destroy)
.subscribe(
data => {
this.user = data;
console.log('Main : ', this.user);
}
);
}
ngOnDestroy() {
this._destroy.next();
this._destroy.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5436 次 |
| 最近记录: |