【问题标题】:Angular2 event.next not triggered after http responsehttp响应后未触发Angular2 event.next
【发布时间】:2016-06-26 16:06:52
【问题描述】:

我有一个奇怪的情况。我有导航组件,我只想在用户登录时显示。我正在尝试使用默认为 false 的变量来管理它,当用户登录时,该值为 true 并且菜单可见。

目前的情况是,当用户点击 MenuComponent 上的注销链接时,会发出事件并且值发生变化。但是在登录时,在http响应之后,它没有被触发。

这里是菜单组件:

import { Component, OnInit } from '@angular/core';
import { UserService } from './../user/user.service';
import { Router } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-navigation',
  templateUrl: 'navigation.component.html',
  styleUrls: ['navigation.component.css'],
  providers: [UserService]
})
export class NavigationComponent implements OnInit {
  public menuStatus;
  constructor(private userService: UserService, private router: Router) {
    this.menuStatus = userService.isLoggedIn();
  }
  ngOnInit() {
    this.userService.userLoggedOut$.subscribe(data => {
      console.log('userLoggedOut subscribe');
      this.menuStatus = data;
    });

    this.userService.userLoggedIn$.subscribe(data => {
      console.log('userLoggedIn subscribe');
      this.menuStatus = data;
    });
  }
  logout() {
    this.userService.userLogout();
    this.router.navigate(['/login']);
  }
}

在此,注销按钮点击触发注销功能。用户服务 userLogout 函数具有事件发射器。这是事件发射器:

import {Injectable} from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Subject } from 'rxjs/Subject';
import { Config } from './../shared/config';

@Injectable()
export class UserService {
  private loggedIn;
  private userLoginUpURL;
  private userLoggedInEvent = new Subject();
  private userLoggedOutEvent = new Subject();

  userLoggedIn$ = this.userLoggedInEvent.asObservable();
  userLoggedOut$ = this.userLoggedOutEvent.asObservable();

  constructor(private http: Http, private config: Config) {
    this.loggedIn = false;
    this.loggedIn = !!localStorage.getItem('access_token');
    this.userLoginUpURL = this.config.loginUrl;
  }

  getUserObject() {
    return JSON.parse(localStorage.getItem('user_object'));
  }

  userLogin(userLoginDetails) {
    let headers = new Headers({
      'Content-Type': 'application/json'
    });

    let postData = {
      email: userLoginDetails.email,
      password: userLoginDetails.password
    };

    return this.http
      .post(this.userLoginUpURL, JSON.stringify(postData), {headers: headers})
      .toPromise()
      .then(res => {
        localStorage.setItem('access_token', res.json().access_token.access_token);
        localStorage.setItem('user_object', JSON.stringify(res.json().user));
        this.loggedIn = true;
        this.userLoggedInEvent.next(this.loggedIn);
        return res.json();
      })
      .catch(this.handleError);
  }

  userLogout() {
    // destroy the local storage variabled
    localStorage.removeItem('access_token');
    localStorage.removeItem('user_object');

    // setup the login status to false
    this.loggedIn = false;
    this.userLoggedOutEvent.next(false);
  }

  isLoggedIn() {
    return this.loggedIn;
  }

  private handleError(error: any) {
    return Promise.reject(error.message || error);
  }
}

问题是,当我调用 this.userLoggedInEvent.next(this.loggedIn) 登录后,事件不会触发。

有人可以帮忙吗?有任何简单的修复方法,我可以刷新窗口并将用户重定向到仪表板,但我不想刷新页面并以正确的方式进行操作。请帮忙。

【问题讨论】:

  • 你从哪里给userLogin()打电话?
  • userLogin() 是通过 LoginComponent 内部的一个函数调用的,该函数具有登录功能。您认为该代码也会有所帮助吗?让我知道,如果需要,我会添加。

标签: angular observable dom-events


【解决方案1】:

确保您在一个公共父级(根组件)上只提供一次UserService,否则不同的组件将获得不同的实例,并且在一个实例上侦听同时在另一个实例上发射不会取得太多效果;-)

【讨论】:

  • 好吧,如果我在 main.ts 组件中添加用户服务,然后在我的菜单组件中添加,如果我通过构造函数调用它...可以吗?
  • 不确定您所说的“添加”是什么意思。如果你想共享一个实例,你不能将它添加到两个组件的提供者中。
  • 你能告诉我怎么做吗
  • 做什么? . . . . .
  • 嘿,Gunter Zochbauer……谢谢你的提示……是的,它工作得很好。我也在 LoginComponent 和 MenuComponent 内部调用用户服务。我认为那是罪魁祸首。我将它作为提供程序从 MenuComponent 和 LoginComponent 中删除,并将其加载到 main.ts 中并且它可以工作。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2019-07-26
  • 2016-07-23
  • 2016-02-29
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
相关资源
最近更新 更多