2017-12-27 107 views
1

我是Angular的新手。我正在嘗試授權並面臨以下任務:如何在傳播中使用observables

有一種服務從前端獲取用戶。我想將此用戶存儲在服務中。爲此,我使用checkUser()函數。接下來,從組件中,我想訪問這個變量,當它在服務中發生變化時,組件接收到這些變化。我認爲我可以在服務中使用Observable(getCurrentUser()函數)。但是這個組件沒有任何東西。你能告訴我什麼是錯的,以及我可以如何實現這一點?謝謝你的建議。

服務:

const API_URL = environment.apiUrl; 

@Injectable() 
export class AuthService { 
    // public user: Account; 
    public user: Account; 

    constructor(private http: HttpClient) { 
    this.checkUser(); 
    const intervalId = setInterval(() => { 
     console.log('Auth: ', this.user); 
    }, 2000); 


    } 

    checkUser() { 
    return this.http 
     .get<Account>(API_URL + '/get_user', { withCredentials: true }) 
     .take(1) 
     .subscribe(user => { 
     this.user = user; 
     console.log(this.user); 
     }); 

    } 

    login(user) { 
    this.http 
     .post<Account>(API_URL + '/login', user, { withCredentials: true 
}).take(1) 
     // .catch(this.handleError) 
     .subscribe(response => { 
     console.log('Resp: ', response); 
     this.checkUser(); 
     }); 
    } 


    getCurrentUser(): Observable<Account> { 
    return Observable.of(this.user); 
    } 

    private handleError(error: Response | any) { 
    console.error('ApiService::handleError', error); 
    return Observable.throw(error); 
    } 

} 

組件:

@Component({ 
    selector: 'app-bs-navbar', 
    templateUrl: './bs-navbar.component.html', 
    styleUrls: ['./bs-navbar.component.css'] 
}) 
export class BsNavbarComponent implements OnInit { 
    // public user$: Observable<Account>; 
    public user: Account; 

    constructor(private authService: AuthService) { 
    const intervalId = setInterval(() => { 
     console.log(this.user); 
    }, 2000); 


    } 

    ngOnInit() { 
    this.authService.getCurrentUser(). 
     subscribe(user => { 
     this.user = user; 
     console.log('Navbar: ', user); 
     }); 

    } 
} 
+0

你能否提供一個有效的Plunkr? –

+0

我想要,但從未使用它,後端在Go上寫入。這裏是當前的github版本:https://github.com/therox/trans – TheROX

回答

1

可能是值得約Subject興趣?

服務代碼:

const API_URL = environment.apiUrl; 

@Injectable() 
export class AuthService { 
    private user: Subject<Account> = new Subject(); 

    constructor(private http: HttpClient) { 
     this.checkUser(); 
    } 

    checkUser() { 
     return this.http 
      .get<Account>(API_URL + '/get_user', { withCredentials: true }) 
      .take(1) 
      .subscribe(user => { 
       this.user.next(user); 
      }); 
    } 

    login(user) { 
     this.http 
      .post<Account>(API_URL + '/login', user, { withCredentials: true }) 
      .take(1) 
      .subscribe(response => { 
       this.checkUser(); 
      }); 
    } 

    getCurrentUser(): Observable { 
     return this.user.asObservable(); 
    } 

    private handleError(error: Response | any) { 
     return Observable.throw(error); 
    } 
} 

無需更換組件。

+0

非常感謝!而已。 – TheROX