/ / Angular5 - Intercetta modifica di una proprietà pubblica in servizio statico: angolare, dattiloscritto, servizio, angolare5

Angular5 - Intercetta modifica di una proprietà pubblica in servizio statico: angolare, dattiloscritto, servizio, angolare5

Considera di seguire Angular servizio

@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() è invocato da app.component.ts. Inoltre, il costruttore di un altro AppSidebarComponent componente dovrebbe ottenere queste informazioni all'avvio dell'applicazione.

Attualmente lo faccio in questo modo:

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

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

Tuttavia se la proprietà cambia il currentUser proprietà di AppSidebarComponent non viene aggiornato.

Come posso risolvere il problema?

risposte:

1 per risposta № 1

Per casi come questo è comune usare BehaviorSubject da 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
}
}

Quindi nel tuo componente:

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

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