gpt4 book ai didi

组件中的Angular 2重复订阅

转载 作者:行者123 更新时间:2023-12-04 12:26:15 25 4
gpt4 key购买 nike

除了在 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 || { };
}

}

还有一个从用户服务订阅可观察对象的组件......
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 中清理订阅?

最佳答案

如果您只想订阅一次,则需要在模板上使用异步管道,异步管道将自动管理取消订阅。如果您喜欢这种方法,您需要使用智能组件和演示组件来组合您的应用程序。检查这个 answer

另一种取消订阅的方法是创建一个主题,以便订阅将完成,直到主题发出一个值。您应该始终取消订阅,否则会出现内存泄漏。

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();
}

}

关于组件中的Angular 2重复订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41709655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com