【发布时间】:2017-07-04 21:00:11
【问题描述】:
这是我的应用程序的主页。如果有人在未登录时尝试访问页面,它将被重定向到。
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;
}
});
}
}
我在尝试重定向到的任何页面上都遇到了同样的问题。有
的行this.currentUser = this._auth.getCurrentUser().subscribe(result => {
this.currentUser = result;
});
错误是
error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: this._auth.getCurrentUser(...).subscribe is not a function
给我一个错误。如果我使用router.navigate(['/']); 重定向到页面,它只会给出错误
我试过navigateByUrl 并得到相同的结果。这是每个页面的顶部,每次我重定向到页面时都会收到错误消息。
这是来自 AuthenticationService 的 getCurrentUser 方法
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;
}
}
【问题讨论】:
-
您应该在每个组件中导入 authProvider(或在某些共享服务中导入)。在每个组件中,您必须将 auth 对象传递给构造函数,以使其在(重定向后新实例化的)组件中可用
-
@Rienk 我更新了我的问题。我确实在每个页面上导入它,并将其包含在我的构造函数中,如上所示。
-
请发布完整的组件,信息太少。我唯一不明白的是你的路由目标中的点(./): this._router.navigate(['./encounter-billing/' + index]);
-
当
this.currentUser不是null时,您不会从getCurrentUser返回 observable,只有当它是null时才返回。 -
把
return this.currentUser;改成return Observable.of(this.currentUser);
标签: javascript angular typescript angular2-routing angular2-services