【问题标题】:Why can´t I work with this Object outside the ngOnInit() Method?为什么我不能在 ngOnInit() 方法之外使用这个对象?
【发布时间】:2017-09-02 20:57:01
【问题描述】:

我正在从我的服务器获取一些数据,并希望在 .ts 文件中对其进行一些处理。到目前为止,这是我对 Typescript/angular 不了解的基本知识......希望有人可以在这里帮助我

user: any;

public doStuff(){
    alert(this.user.username);
 }

用户是具有不同属性的对象,例如在 ngOnInit() 块上初始化的“用户名”。 我在 ngOnInit 方法中设置它。服务注入正确,以下代码正常运行

ngOnInit() {

this.authService.getProfile().subscribe(profile =>{
    this.user= profile.user;
    this.initStuff();

  },
  err => {
    console.log(err);
    return false;
  });
 }

它会按预期提醒用户名...但是一旦我将 doStuff() 方法的方法调用移到该代码块之外,它就不再工作了,在浏览器控制台中显示“无法读取属性”未定义的值' - 为什么它是未定义的?如果我在 component.html 中使用 {{user.username}},它也会显示正确的用户名

ngOnInit() {

this.authService.getProfile().subscribe(profile =>{
    this.user= profile.user;
  },
  err => {
    console.log(err);
    return false;
  });
    this.initStuff(); // why cant i call it here? Its where I also call all of my other doStuff() methods
 }

【问题讨论】:

    标签: javascript json angular typescript mean-stack


    【解决方案1】:

    它不起作用,因为 getProfile() 是异步操作。如果你想对服务器数据做一些事情,它必须在 subscribe next() 方法中完成。当 aysnc 操作有新值时调用 next 方法。

    如果你在 next() 方法之外调用 initStuff(),它将立即执行,这就是为什么你得到“无法读取未定义的 peoperty 'value'”的原因。

    希望对你有帮助。

    【讨论】:

    • 将 initStuff() 方法调用留在 subscribe() 中,你能解释一下“但是我该如何使用另一个方法中的参数 'user' 呢?”贴一些例子。
    【解决方案2】:

    如果我理解正确,您正在尝试调用尚未收到的数据,这是您控制台错误的原因。在所描述的函数中,您使用 Observable (RxJs) 并且函数是异步的。如果你想对变量 'profile' 做一些事情,你应该将操作放在 Observable 回调中,这意味着在 body subscribe 的 call 方法中。

    【讨论】:

      猜你喜欢
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 2020-08-10
      • 2012-08-17
      相关资源
      最近更新 更多