无法在我的Angular 4.x应用程序中的ngOnInit()之外访问我的json响应数据

时间:2018-01-25 15:12:12

标签: angular ngoninit

我有一个带有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?

3 个答案:

答案 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
    }
}