【问题标题】:angular2 share class propertiesangular2 共享类属性
【发布时间】:2017-10-08 11:42:50
【问题描述】:

我有应用组件(用于导航标题)和身份验证组件(用于登录)。

他们需要两个“isLoggedIn”属性,这对于应用程序将其“登录”按钮更改为“注销”以及验证在登录后阻止登录尝试很有用。

但是不知道能不能导出?从一个组件到另一个组件的属性。

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

如何让他们共享“isLoggedIn”属性?

这是我的身份验证组件和带有用户身份验证服务的应用组件。

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

}

【问题讨论】:

    标签: javascript angular angular2-services class-properties


    【解决方案1】:

    您可以在此处使用 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;
       });
    }
    

    【讨论】:

    • 您的所有组件都应该从一个地方获取登录值,根据我的回答,这是您服务中的 BehaviorSubject。他们都可以轻松订阅它,然后采取相应的行动。如果您将我的答案与您的代码结合起来,您可以轻松实现这一目标。您的行
      会很好,因为您可以在 loggedIn 值的 subscribe 块中设置此值。完成所有操作后,您将需要考虑实施警卫来阻止路线:blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 2017-01-04
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多