为什么我不能在 ngOnInit() 方法之外使用这个对象?

Why can´t I work with this Object outside the ngOnInit() Method?

我正在从我的服务器获取一些数据,并想在 .ts 文件中用它做一些事情。到目前为止,我对Typescript/angular还不太了解...希望有人能在这里帮助我

user: any;

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

用户是一个具有不同属性的对象,如 'username',在 ngOnInit() 块上初始化。 我在 ngOnInit 方法中设置它。服务注入正确,以下代码正常工作

ngOnInit() {

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

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

它正在按预期提醒用户名...但是一旦我将 doStuff() 方法的方法调用移到该代码块之外,它就不再工作了,在浏览器控制台中显示 "cannot read property 'value' of undefined" - 为什么它是未定义的?如果我在 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
 }

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

如果您在 next() 方法之外调用 initStuff() ,它将立即执行,这就是您获得 "cannot read peoperty 'value' of undefined".

的原因

希望对您有所帮助。

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