如何在Promise中更新全局变量并在其他组件中恢复使用

时间:2018-12-20 11:46:59

标签: angular typescript global-variables es6-promise angular-promise

问题是我有一个要显示的用户名,但无法获取承诺以外的数据。

我创建了一个user.service.ts并将其作为提供程序包含在app.module.ts中。然后在app.component.ts中,将user设置为等于返回的数据,但是它不起作用。为什么不能在像这样的承诺中更新全局变量?

user.service.ts

import { Injectable } from '@angular/core';
import { AuthGuardService } from './auth-guard.service';

@Injectable({
  providedIn: 'root'
})
export class UserService {

public user: string;

constructor(private authService: AuthGuardService) {

  this.authService.getAuthStatus().then(data => {
    console.log(data.username)
    this.user = data.username;
    return this.user;
  });
 }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, Route  } from '@angular/router';
import { AuthGuardService } from './services/auth-guard.service';
import { CookieService } from 'ngx-cookie';
import { Window } from 'selenium-webdriver';
import { UserService } from './services/user.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Fordringsadministration';

private previousUrl: string = undefined;
private currentUrl: string = undefined;
public user: string;

   constructor(
     private router: Router,
     public userService: UserService,
     private cookie: CookieService
  ) {

  ngOnInit() {
    this.user = this.userService.user;
    console.log(this.user)
  }
}

预期结果应为sti-admin-这是当前登录的用户。但是我没有定义?因此this.user是未定义的。

3 个答案:

答案 0 :(得分:2)

getAuthStatus()是一个异步过程。因此,同时运行AppComponent的ngOnInit中的代码,可能尚未设置用户。

您可以通过将调试点放置在promise的成功处理程序中和ngOnInit中来验证这一点。为了满足您的要求,您可以在userService中使用一个getUser()方法,该方法返回一个Promise(基本上包含UserService的构造函数中存在的逻辑)。

这可以在您的AppComponent中处理。此外,您可以缓存它并相应地修改逻辑。

答案 1 :(得分:0)

您可以创建一个可观察的事件并触发一个事件,以便组件可以侦听并解析用户名

在服务中

private _onUserName: Subject<string> = new Subject();
onUserName: Observable<string> = this._onUserName.asObservable();

constructor(private authService: AuthGuardService) {

  this.authService.getAuthStatus().then(data => {
    console.log(data.username)
    this.user = data.username; 
    this._onUserName.next() //fire the event
  });
}

并在组件中订阅它

  ngOnInit() {
     this.userService.onUserName.subscribe(item => { 
        console.log(this.userService.user)
    });
  }

答案 2 :(得分:0)

我想通了-只能将它退还给我。这样,我可以在所有组件中编写this.user。

相关问题