2016-12-12 8 views
3

ユーザーがログインするときにメニューを更新しようとしています。同様の問題に関するいくつかの回答を読みましたが、 。Angular2 observables - ユーザーがログインしたときにsubscribeが変数を更新しない

NAV-bar.component.html:

<li *ngIf="isLoggedIn"><a routerLink="/" (click)="logout($event);"> {{ logoutLabel }}</a></li> 
<li *ngIf="!isLoggedIn"><a routerLink="/login (click)="showPopup($event);">{{ loginLabel }}</a></li> 

でのnav-bar.component.tsは、私は、ログイン・フォームをモーダルを開き、またから変数に変更を探しますlogin.service

import { SuPopupLoginComponent } from '../shared/su-popup-login/su-popup-login.component'; 
import { LoginService } from '../login/login.service'; 
...imports... 

@Component({ 
    selector: 'app-nav-bar', 
    templateUrl: './nav-bar.component.html', 
    styleUrls: ['./nav-bar.component.scss'] 
}) 
export class NavBarComponent implements OnInit { 
    loginLabel: string; 
    public isLoggedIn: boolean; 

    constructor(private loginService: LoginService, private suPopupLoginComponent: SuPopupLoginComponent) { 
     loginService.getIsLoggedIn.subscribe((bool: boolean) => { 
     this.isLoggedIn = bool; 
     console.log('NavBarComponent', this.isLoggedIn); 
     }); 
    } 

    showPopup(event) { 
     event.preventDefault(); 
     this.suPopupLoginComponent.showPopup(); 

     If I call login here It works just as expected 

     // this.loginService.login('[email protected]', 'Test123') 
     //  .subscribe(
     //  data => { 
     //   if (data) { // If login was successful data is true. 
     //   let redirect = 'license-overview'; 
     //   this.router.navigate([redirect]); 

     //   } 
     //  } 
     //  ); 
    } 

    logout(event) { 
     event.preventDefault(); 
     this.loginService.logout(); 
    } 
    ngOnInit() { } 
} 

SU-ポップアップlogin.component.ts - -フォームにログインし、機能をログインすることを呼び出します。

import { LoginService } from '../../login/login.service'; 
import { Injector } from '@angular/core'; 

@Component({ 
    selector: 'su-popup-login', 
    templateUrl: './su-popup-login.component.html', 
    styleUrls: ['./su-popup-login.component.scss'], 
    providers: [LoginService] 
}) 

export class SuPopupLoginComponent implements OnInit { 

    constructor(private loginService: LoginService, private injector: Injector) { } 

    public showPopup() { 
    Css and showing modal 
    } 

    login(event, mail, password) { 
     this.loginService.login(mail, password) 
     .subscribe(
      data => { 

       if (data) { // If login was successful data is true. 

       // Navigate to view after login success. 
       this.router = this.injector.get(Router); 
       let redirect = 'license-overview'; 
       this.router.navigate([redirect]); 

     } 
     } 
    ); 
    } 

login.service.ts

import { Injectable } from '@angular/core'; 
import { Http, Headers, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 

@Injectable() 
export class LoginService { 
    private isLoggedInSource = new BehaviorSubject<boolean>(localStorage.getItem('currentUser') ? true : false); 
    public _isLoggedIn: Observable<boolean> = this.isLoggedInSource.asObservable(); 

    constructor(private http: Http) { } 

    private isLoggedIn(logged: boolean) { 
     this.isLoggedInSource.next(logged); 
    } 

    get getIsLoggedIn() { 
     return this._isLoggedIn; 
    } 

    login = (mail: string, password: string): Observable<boolean> => { 
    let loginUrl = '/api/authenticate'; 
    let body = JSON.stringify({ mail, password }); 

    return this.http.post(loginUrl, body) 
     .map((response: Response) => { 
      let user = response.json(); 

      if (user && user.tokenId) { 
      this.isLoggedIn(true); 

      // Add to local storage 
      localStorage.setItem('currentUser', JSON.stringify({ mail: mail, tokenId: user.tokenId })); 
      return true; // Login success 
     } 
     else { 
      return false; // Login failed 
     } 
     }); 
    } 
} 

それは私がNAV-bar.componentからthis.loginService.login('user', 'pass')を呼び出す場合正常に動作しますが、ログインがSU-ポップアップログインから呼び出されていないとき.component.ts。また、this.loginService.logout()からnav-bar.component.tsが問題なく動作します。

subscribeコールは、ログイン/ログアウトの呼び出しと同じコンポーネント内になければなりませんか?もしそうなら、私はObservablesの仕組みを理解していないと思います。

ありがとうございました。 su-popup-login.component.ts

答えて

1

providers: [LoginService]LoginServiceの異なるインスタンスを作成しました。それを動作させるために

、あなたのngModule of appcomponentまたはcoremoduleproviders: [LoginService]その使用を避け、providers: [LoginService]を削除するには、両方のコンポーネントがLoginService

の単一のインスタンスを共有することを確認する必要がありますからsu-popup-login.component.ts

+0

ああ、それです!どうもありがとうございます! – bagling

関連する問題