2017-02-18 28 views
0

我有一個應用程序,它包括登錄和家庭組成,角2:無法獲得另一個組件的令牌存儲在本地storege

login.service.ts

let body = JSON.stringify(data); 
    console.log("logged in user",body); 
    return this._http.post('http://localhost:8080/api/user/authenticate', body, { headers: contentHeaders }) 
    .map(res => res.json()) 

    .map((res) => { 
     var token1:any = res; 
     console.log(token1); 
     if (token1.success) { 
      localStorage.setItem('auth_token', token1.token); 
      this.LoggedIn = true; 
     } 

     return res.success; 
     }); 
} 
isLoggedIn() { 

    return this.LoggedIn; 
    } 
在此

服務我公司在可變TOKEN1和isLogged方法獲得令牌包含

constructor(private _http: Http) { 
    this.LoggedIn = !!localStorage.getItem('auth_token'); } 

Login.component.ts

login(event, username, password) 
    { 

    this.loginService.login(username, password) 
    .subscribe(
     response => { 
     this.router.navigate(['/home']); 
     alert("login successfull"); 
     }, 
     error => { 
      alert(error.text()); 
      console.log(error.text()); 
     } 
    ); 

從這個登錄我可以能夠進行身份驗證,並和其路由到家庭成分,

Home.serice.ts

getClientList() 
    { 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    let authToken = localStorage.getItem('auth_token'); 
    headers.append('X-auth-Token', 'authToken') 
     return this._http.get('http://localhost:8080/api/v1/client/list?isClient=Y', {headers}) 
     .map(res => res.json()) 
    } 

Home.component.ts

onTestGet() 
    { 
      this._httpService.getClientList() 
      .subscribe(
      data => this.getData = JSON.stringify(data), 
      error => alert(error), 
      () => console.log("finished") 


    ); 
    } 

現在的問題是我怎麼可以訪問該令牌在家庭組件中的token1 varible(登錄)我厭倦了getitem token.but我得到的令牌null.please任何人都幫助我。

在此先感謝

回答

0
localStorage.getItem('auth_token') 

這應該工作,但是你得到空,因爲數據的生命週期不同。

我建議你爲此目的使用主題構造,尤其是你已經有數據服務。

例子:

loginInfo$ = new Subject(); 
private _logininfo = null; 
getLoginData() { 
    if(!_logininfo) { 
     this.http..... { this._loginInfo = data; 
          this.loginInfo$.next(data); } 
     return this.loginInfo$.first() 
    } 
    else return Observable.of(this._logininfo); 
} 

所以,現在,您的數據和處理程序丟失登錄的同時存儲服務。

+0

是的,我已經在getclientList()方法中的home.service.ts累了,但我無法訪問令牌。 –

+0

@PramodRamadand如果您在使用getClientList的時候尚未將其存入存儲,那麼它爲空。您可以添加一些調試信息到問題:console.log(token1);和getClientLIst中的console.log(authToken)? – laser

相關問題