0

我有一个 Angular 4.x 应用程序,其中包含一个正在发送的 http 请求,并且我从端点取回了有效的 json(我可以在初始 console.log 中看到) - 问题是我无法在外部看到这些数据ngOnInit() 就在我有 console.log 的下面

谁能建议问题是什么?

export class SidebarComponent implements OnInit {

  constructor(private http: HttpClient, private userService: UserService) { }

   ngOnInit() {

    this.http.get('https://dev.myapp.com/api/angularfour/auth',
        { params: new HttpParams()
            .set('token', this.userService.getAuth().__token)
            .set('apiversion', '1')
            .set('appid', this.userService.getAuth().appid) })
        .subscribe(data => {
            console.log('data', data); // can see this data
        });
    }

console.log('menu data outside init', data); // cannot see this data?
4

3 回答 3

1

在您的示例中,请注意变量的范围;数据只存在于 subscribe 方法中,你需要在你的类中定义一个全局变量,例如:

在导出类下添加:

mydata : any;

并在您的订阅方法中:

this.mydata = data;

所以你可以在方法之外访问数据:

console.log('menu data outside init', this.mydata); 
于 2018-01-25T15:17:45.367 回答
1

如果要在ngOnInit块之外访问它,则需要在组件上设置一个属性。现在,您的data变量的范围是subscribengOnInit方法中的块。

尝试这样的事情:

export class SidebarComponent implements OnInit {

constructor(private http: HttpClient, private userService: UserService) { }

data: any; // property for data

ngOnInit() {

this.http.get('https://dev.myapp.com/api/angularfour/auth',
    { params: new HttpParams()
        .set('token', this.userService.getAuth().__token)
        .set('apiversion', '1')
        .set('appid', this.userService.getAuth().appid) })
    .subscribe(data => {
        this.data = data; // save the most recent data in the data property
        console.log('data', data); // can see this data
    });
}

console.log('menu data outside init', this.data); // your data
于 2018-01-25T15:17:47.357 回答
1
export class SidebarComponent implements OnInit {
   myData:any;

  constructor(private http: HttpClient, private userService: UserService) { }

   ngOnInit() {

    this.http.get('https://dev.myapp.com/api/angularfour/auth',
        { params: new HttpParams()
            .set('token', this.userService.getAuth().__token)
            .set('apiversion', '1')
            .set('appid', this.userService.getAuth().appid) })
        .subscribe(data => {
            console.log('data', data); // can see this data
            this.myData=data;
        });
    }

   buttonClick(){
     console.log('menu data outside init',  this.myData); 
     // this will only work after the async call has finished
    }
}
于 2018-01-25T15:18:54.033 回答