Angular5 - 在静态服务中拦截更改 public 属性

Angular5 - Intercept change a public property in static service

考虑关注 Angular 服务

@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()app.component.ts 调用。 此外,另一个 AppSidebarComponent 组件的构造函数应该在应用程序启动时获取此信息。

目前我是这样做的:

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

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

但是,如果 属性 发生变化,AppSidebarComponentcurrentUser 属性 不会更新。

我该如何解决这个问题?

对于这种情况,通常使用 rxjs 中的 BehaviorSubject:

@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
     }
}

然后在你的组件中:

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

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