从angular -oidc-client中的app.component获取数据时,this.user是未定义的

问题描述

我在oidc-client.js项目中使用angular

现在,用户可以登录和注销,它可以正常工作。唯一的问题是,当我想在app.component中调用服务时,在拦截器中用户未通过身份验证。

auth.service是:

    Injectable({
  providedIn: 'root'
})
export class AuthService extends BaseService {


  private _authNavStatusSource = new BehaviorSubject<boolean>(false);

  authNavStatus$ = this._authNavStatusSource.asObservable();

  private manager = new UserManager(getClientSettings());
  private user: User | null;


  constructor(private http: HttpClient) {
    super();   
    this.manager.getUser().then(user => {
      this.user = user;
      this._authNavStatusSource.next(this.isAuthenticated());
    });
  }

  login() {
    return this.manager.signinRedirect();
  }

  async completeAuthentication() {
    this.user = await this.manager.signinRedirectCallback();
    this._authNavStatusSource.next(this.isAuthenticated());
  }


  isAuthenticated(): boolean {
    return this.user != null && !this.user.expired;
  }

  get authorizationHeaderValue(): string {
    return `${this.user.token_type} ${this.user.access_token}`;
  }

  async signout() {
    await this.manager.signoutRedirect();
  }
}

export function getClientSettings(): UserManagerSettings {
  return {
    authority:environment.authApiURI,client_id: 'medilloxdashboard',redirect_uri: environment.redirect_uri,post_logout_redirect_uri: environment.postLogoutRedirectUri,response_type: "id_token token",scope: "openid spa profile",filterProtocolClaims: true,loadUserInfo: true,automaticSilentRenew: true,silent_redirect_uri:environment.silentRedirectUri,userStore: new WebStorageStateStore({ store: localStorage })
  };
}

我写了一个拦截器,将令牌添加到所有这样的请求中:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private authorizationHeader = "Authorization";

  constructor(
    private authService: AuthService,private router: Router) { }
  intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      headers: request.headers.set(this.authorizationHeader,this.authService.authorizationHeaderValue)
    });
    return next.handle(request);
  }

}

AuthServiceAuthInterceptor已在Core nodule中注册。

App.Compoentn中,我调用这样的服务,该服务称为REST api

    export class AppComponent implements OnInit {

  title = 'myapp';
  version: string;

     constructor(
        private router: Router,private dashboardService: DashboardService) {
        this.version = environment.version;
      }
    
      ngOnInit(): void {
        this.dashboardService.getDashboards().subscribe();
      }
    }

发生此呼叫时,我得到getDashboards failed: this.user is undefined 但我在其他组件中完全称呼此服务,并且效果很好。

调用此服务并获得结果的

组件位于它们的 模块。

问题出在哪里?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)