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

时间:2018-03-09 02:04:59

标签: angular2-services angular2-components

我花了大约5个小时试图学习如何实现可观察量,主题,行为主题等,并且似乎无法完全掌握如何做到这一点。基本上,我有一个登录组件。登录组件调用auth.service.ts,它进行http调用以验证用户。

成功登录用户后,我转到another.component.ts。我希望another.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

我似乎无法弄清楚如何将所有这些拼凑在一起。任何帮助或见解将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

*** 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;
    })