在Angular 2中重定向组件时出错

时间:2017-07-04 21:00:12

标签: javascript angular typescript angular2-routing angular2-services

这是我的应用的主页。如果有人在未登录时尝试访问该页面,则会重定向到该页面。

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;
        }
  }

1 个答案:

答案 0 :(得分:1)

不是在用户对象已经存在时返回它,而是使用Observable of运算符对其进行转换以返回Observable。

在身份验证服务中将return this.currentUser;更改为return Observable.of(this.currentUser);

这也有点过了:

this.currentUser = this._auth.getCurrentUser().subscribe(result => {
  this.currentUser = result;
});

currentUser设置为Subscription的{​​{1}},然后结果(getCurrentUser()返回subscribe())。