/ / Angular5 - Przechwytuje zmianę właściwości publicznej w usłudze statycznej - kątowa, maszynopis, usługa, kątowa5

Angular5 - Intercept powoduje zmianę właściwości publicznej w usłudze statycznej - kątowa, maszynopis, usługa, kątowa5

Zastanów się nad tym Angular usługa

@Injectable()
export class AuthService {
public userConnected: UserManageInfo;
getManageInfo(): Observable<UserManageInfo> {

return this.httpClient
.get("api/Account/ManageInfo", { headers: this.getCustomHeaders() })
.catch((error: Response) => {
if (error.status == 401)
return this.logout();
return Observable.throw(error)
})
.map((response: any) => {
this.userConnected = response;
return this.userConnected;
});
}
}

getManageInfo() jest wywoływana z app.component.ts. Ponadto konstruktor innego AppSidebarComponent składnik powinien uzyskać te informacje podczas uruchamiania aplikacji.

Obecnie robię to w następujący sposób:

export class AppSidebarComponent implements OnInit {
public currentUser: UserManageInfo = new UserManageInfo();

constructor(private authService: AuthService) {
this.currentUser = this.authService.userConnected;
}
}

Jednak, jeśli właściwość zmieni nazwę currentUser własność AppSidebarComponent nie jest aktualizowany.

Jak mogę rozwiązać problem?

Odpowiedzi:

1 dla odpowiedzi № 1

W takich przypadkach często używa się BehaviorSubject z rxjs:

@Injectable()
export class AuthService {
public UserConnected = new BehaviorSubject<UserManageInfo>(null); // create it and initialise will null, for example

getManageInfo(): Observable<UserManageInfo> {
return this.httpClient
.get("api/Account/ManageInfo", { headers: this.getCustomHeaders() })
.catch((error: Response) => {
if (error.status == 401)
return this.logout();
return Observable.throw(error)
})
.do(response => this.UserConnected.next(response)); // make sure you subscribe to this observable somewhere so that it"s executed
}
}

Następnie w swoim komponencie:

export class AppSidebarComponent implements OnInit {
public CurrentUser: UserManageInfo = new UserManageInfo();

constructor(private authService: AuthService) {
this.authService.UserConnected.subscribe((data: UserManageInfo) => {
this.CurrentUser = data;
});
}
}