angular2共享类属性

时间:2017-05-10 01:09:34

标签: javascript angular angular2-services class-properties

我有app组件(用于nav标头)和auth组件(用于登录)。

他们需要" isLoggedIn"属性可以用于应用程序更改其"登录"按钮到"退出"以及auth在登录后阻止登录尝试。

但我不知道我是否可以出口?从一个组件到另一个组件的属性。

我知道我可以使用服务,但应用程序没有适当的方法来订阅用户服务的映射数据。

如何让他们分享" isLoggedIn"属性?

以下是我的auth组件和app组件,其中包含用户身份验证服务。

export class AuthComponent {

  private username = '';

  private password = '';

  private remembered: boolean = false;

  isLoggedIn: boolean; 

  constructor(private userAuthenticationService: UserAuthenticationService) {}

  onsubmit() { 
    this.userAuthenticationService
    .logIn({ username: this.username, password: this.password })
    .subscribe(response => {
      this.isLoggedIn = response["success"];
    });
  }

}

//auth.component.html
<div class="loginbox">
  <header>MAILBOY</header>
  <form *ngIf="!isLoggedIn; else loggedInMessage">
    <input type="text" [(ngModel)]="username" name="username" id="email" placeholder="이메일 주소"/>
    <input type="password" [(ngModel)]="password" name="password" id="password" placeholder="비밀번호"/>
    <label for="remember"><input type="checkbox" id="remember" [checked]="remembered" (change)="remembered = !remembered" />이메일 저장</label>
    <button class="login" (click)="onsubmit()">로그인</button>
    <h3>처음이신가요?</h3><button class="register"><a href="/register">회원가입</a></button>
  </form>  
  <ng-template #loggedInMessage>
    <h1>환영합니다! 메일 수신 여부를 설정해주세요.</h1>
  </ng-template>
</div>





export class AppComponent {

  isLoggedIn = 'false';

  constructor(private userAuthenticationService: UserAuthenticationService) { }

}

//app.component.html
<div class="headerSpacing">
        <nav>
            <a routerLink="/home" routerLinkActive="active">홈</a>
            <a *ngIf="isLoggedIn; else loggedInMessage" routerLink="/auth" routerLinkActive="active">로그인</a>   
                    <ng-template #loggedInMessage>
                            <a (click)="logOut()">로그아웃</a>
                    </ng-template>
            <a routerLink="/mail-setting" routerLinkActive="active">메일 수신 설정</a>
        </nav>
    </div>
    <router-outlet></router-outlet>

最后是我的用户身份验证服务

@Injectable()
export class UserAuthenticationService {

  headers = new Headers({
    'Content-Type': 'application/json'
  });

  constructor(private http: Http) { }

  /*
    body: {
      username,
      password,
    }
  */
  logIn(user: Object) {
    return this.http
    .post('/auth/login', JSON.stringify(user),
    { headers: this.headers })
    .map(data => { console.log(data);
      return data.json() });
  }

  private handleError(error: any): Promise<any> {
    console.log('An error occurred ', error);
    return Promise.reject(error.message || error);
  }

}

1 个答案:

答案 0 :(得分:2)

您可以在此处使用BehaviorSubject。

在UserAuthenticationService中:

import { BehaviorSubject } from 'rxjs';

export class UserAuthenticationService {
   private loggedIn = new BehaviorSubject(false);

   // call this when you want to set loggedIn to true
   login() {
     this.loggedIn.next(true);
   }

   getIsLoggedIn() {
     return this.loggedIn;
   }
}

在app或auth组件或您需要该值的任何组件中,您可以订阅它:

constructor(private userAuthenticationService: UserAuthenticationService) {
   userAuthenticationService.getIsLoggedIn().subscribe(bool => {
     // use bool value here, you can set local var
     // this.isLoggedIn = bool;
   });
}