This is the home page of my app. It gets redirected to if someone tries to access a page when they aren't logged in.
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { AuthenticationService } from '../_services/authentication.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
model: any = { username: "", password: "" };
loading = false;
error = '';
isLoggedIn = false;
public currentUser: any = null;
constructor(private _auth: AuthenticationService, private router: Router) { }
ngOnInit() {
if(this._auth.isLoggedIn()) {
this.isLoggedIn = true;
this.router.navigate(['/census']);
}
else {
}
this.currentUser = this._auth.getCurrentUser().subscribe(result => {
this.currentUser = result;
});
/*let timer = Observable.timer(29000, 29000);
timer.subscribe(t => {
//this.refresh();
});*/
}
login() {
this.loading = true;
this._auth.login(this.model.username, this.model.password)
.subscribe(result => {
if (result === true) {
// login successful
this.isLoggedIn = true;
this.router.navigate(['/census']);
} else {
// login failed
this.error = 'Username or password is incorrect';
this.loading = false;
}
});
}
}
I have the same problem on any page I try redirecting to. The line that has
this.currentUser = this._auth.getCurrentUser().subscribe(result => {
this.currentUser = result;
});
The error is
error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: this._auth.getCurrentUser(...).subscribe is not a function
Gives me an error. It only gives an error if I redirected to the page using router.navigate(['/']);
I've tried navigateByUrl
and get the same result. This is on the top of every page, and I get the error any time I redirect to the page.
This is the getCurrentUser method from the AuthenticationService
getCurrentUser(): Observable<any> {
if (this.currentUser == null) {
let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('token') });
let options = new RequestOptions({ headers: headers });
return this.http.get( this._api.apiUrl + 'users/0', options)
.map((response: Response) => {
this.currentUser = response.json();
return this.currentUser;
});
}
else {
return this.currentUser;
}
}