get方法返回未定义的值虽然在方法内部值不为空

时间:2016-08-10 10:02:06

标签: json angular typescript get

我的方法是

Uri fileUri = getIntent().getData();
        if (!fileUri.getPath().contains("external") && fileUri.getScheme().equals("content")) {
            Cursor cursor = getContentResolver().query(fileUri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } finally {
                cursor.close();
            }
        }if (!fileUri.getPath().contains("external") && fileUri.getScheme().equals("file")) {
            List<String> pathSegments = fileUri.getPathSegments();
            if (pathSegments.size() > 0) {
                fileName = pathSegments.get(pathSegments.size() - 1);
            }
        }

我的json是

getOrganizations() : any[]{

this._http.get(this._url)
        .map(res => res.json())
        .subscribe(
            data => { 
            console.log(data.responseData.org_list);
            return data.responseData.org_list;
            },

打印出[对象]

但是当我从这样的组件中调用这个方法时:

{"status":0,"statusMessage":"Success","responseData":{"org_list":[{"organizationName":"orgName1","summary":"org1Summary"}]},"errors":[]}


console.log(data.responseData.org_list);

我在两个控制台输出中都未定义

这可能是什么原因?

3 个答案:

答案 0 :(得分:0)

你应该这样重构你的方法:

getOrganizations() : any[]{
  return this._http.get(this._url)
    .map(res => res.json())
    .map(data => data.responseData.org_list);
}

并以这种方式称呼它:

constructor(private _service: OrganizationService){
}

ngOnInit(){
  this._service.getOrganizations()
    .subscribe(organizations => {
      this.organizations = organizations;
    });
}

不要忘记observable是异步的,你不能直接返回...

答案 1 :(得分:0)

中没有return
getOrganizations() : any[]{

答案 2 :(得分:0)

由于http调用的异步特性,我建议使用此设置:

getOrganizations(): Observable {
    return this._http.get(this._url)
        .map(res => res.json().responseData.org_list);
}

在您的组件中,只需订阅您的服务方法:

constructor(private _service: OrganizationService){
}

ngOnInit(){
    this._service.getOrganizations()
        .subscribe((data) => {
            this.organizations = data;
            console.log(this.organizations); 
        }
    );     
}