【问题标题】:Error when redirecting between components in Angular 2在Angular 2中的组件之间重定向时出错
【发布时间】: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


【解决方案1】:

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

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

这也有点不对劲:

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

currentUser 被设置为getCurrentUser()Subscription,然后是结果(subscribe() 返回Subscription)。

【讨论】:

  • 你会建议我如何改变它?
  • 订阅?典型的模式是保存订阅(在单独的属性中),然后在 ngOnDestroy 中取消订阅以确保它被删除。
  • 你能给我举个例子吗?我想确保我做对了。
  • 类似这样的答案:stackoverflow.com/a/34926698/3244479
  • 这个答案虽然涉及很多细节并提出了一种更新的方法:stackoverflow.com/a/41177163/3244479
猜你喜欢
  • 2017-07-04
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 2021-10-03
  • 2017-02-11
  • 1970-01-01
相关资源
最近更新 更多