如何在 Angular2 中的组件之间传递当前用户



在过去的~5个小时里,我一直在尝试学习如何实现可观察量、主体、行为主体等,但似乎无法完全掌握如何做到这一点。 本质上,我有一个登录组件。 登录组件调用 auth.service.ts,它进行 http 调用以对用户进行身份验证。

成功登录用户后,我转到另一个.component.ts。 我希望另一个.component.ts可以访问auth.service.ts文件中的this.currentUser。

法典:

** login.component.ts **
// this works -> authenticates user and sends to home page
this.authService.authenticateUser(this.loginUser)
  .subscribe((response) => {
    this.router.navigate([/'homePage']);
  });

** auth.service.ts **
  public signedInUser = new BehaviorSubject<User>(null);
  // gets called when user submits login form
  authenticateUser(user) {
    let route = "http://localhost:3000/login";
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(route, user, { headers: headers })
      .map((response) => {
        ??? set this.signedInUser ???
        return response.json();
      })
      .catch((error)  => {
        return Observable.throw(error.json());
      })
  }

  // I tried implementing this functionality
  // I think one of the issues is I can't figure out where
  // to put this.signedInUser.next();
  subscribeToCurrentUser() {
    return this.signedInUser.asObservable();
  }


** another.component.ts **
// I want access to this.authService.signedInUser
   it currently is undefined
   I even added {{ currentUser.firstName | async }}
   and it didn't work

我似乎不知道如何将所有这些拼凑在一起。 任何帮助或见解将不胜感激。

==== 找到答案 ====

*** login.component.ts ***
this.authService.authenticateUser(this.loginUser);
** auth.service.ts **
  public signedInUser = new BehaviorSubject<User>(null);
  // gets called when user submits login form
  authenticateUser(user) {
    let route = "http://localhost:3000/login";
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(route, user, { headers: headers })
      .map((response) => {
        return response.json();
      })
      .catch((error)  => {
        return Observable.throw(error.json());
      })
      .subscribe((response) => {
        this.currentUser.setCurrentUser(response.user);
      })
  }
  getCurrentUser() {
    return this.signedInUser.asObservable();
  }
  setCurrentUser(user) {
    this.currentUser.next(user);
  }


** another.component.ts **
this.authService.getCurrentUser()
    .subscribe((user) => {
       this.currentUser = user;
    })

相关内容

  • 没有找到相关文章

最新更新