【问题标题】:get method returns undefined value although inside the method the value is not emptyget 方法返回未定义的值,尽管在方法内部该值不为空
【发布时间】:2016-08-10 10:02:06
【问题描述】:

我的方法是

getOrganizations() : any[]{

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

我的 json 是

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


console.log(data.responseData.org_list);

打印出[对象]

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

constructor(private _service: OrganizationService){
}

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

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

这可能是什么原因?

【问题讨论】:

    标签: json angular typescript get


    【解决方案1】:

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

    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;
        });
    }
    

    不要忘记 observables 是异步的,你不能直接返回一些东西......

    【讨论】:

      【解决方案2】:

      你的中没有return

      getOrganizations() : any[]{
      

      【讨论】:

        【解决方案3】:

        由于 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); 
                }
            );     
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-17
          • 2022-12-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-09
          相关资源
          最近更新 更多