我有一个带有http请求的Angular 4.x应用程序正在发送,我从端点返回有效的json(我可以在初始console.log中看到这个) - 问题是我看不到这些数据我在控制台.log
下面的ngOnInit()外面有人能说明问题是什么吗?
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?
答案 0 :(得分:1)
在你的例子中注意变量的范围;数据仅存在于subscribe方法中,您需要在类中定义一个全局变量,例如:
在导出类下添加:
mydata : any;
并在您的订阅方法中:
this.mydata = data;
因此,您可以访问方法外的数据:
console.log('menu data outside init', this.mydata);
答案 1 :(得分:1)
如果要在ngOnInit
块之外访问它,则需要在组件上设置属性。目前,您的data
变量的范围限定为subscribe
方法中的ngOnInit
块。
尝试这样的事情:
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
答案 2 :(得分: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
}
}