Angular 2 http对象如何变量?

时间:2017-05-18 08:50:54

标签: angular typescript

我正在使用此代码:

private ARRAYDATA: any[];
constructor(private http: Http) {
   this.getCards('data.json');
}
getCards(url)
  {
    this.http.get(url)
              .map(response => response.json())
              .subscribe(
                  function(response) {
                    console.log(response); //show object
                  },
                  function(error) { console.log("Error happened" + error)},
                  function() { console.log("the subscription is completed")}
              );
  }

此代码有效,现在我无法理解如何将对象RESPONSE传递给变量ARRAYDATA;请帮帮我! 此代码不起作用:

getCards(url)
  {
    this.http.get(url)
              .map(response => response.json())
              .subscribe(
                  function(response) {
                    console.log(response); //show object
                    this.arraydata = response;
                  },
                  function(error) { console.log("Error happened" + error)},
                  function() { console.log("the subscription is completed")}
              );
              console.log(this.arraydata)// show undefind
  }

我需要在函数外部使用变量ARRAYDATA。就在这里

constructor(private http: Http) {
   this.getCards('data.json');
   console.log(this.ARRAYDATA);
}

3 个答案:

答案 0 :(得分:3)

这里有两个问题。

  1. Http响应返回异步的observable,这意味着您可以在 subscribe 函数中获取数据。

  2. 您正在使用常规函数,这意味着您的this将更改并指向函数对象而不是类。您应该使用Arrow Functions进行回调。 ()=>{}未将函数对象分配给this

    this.http.get(url)
          .map(response => response.json())
          .subscribe(
             (response) => {
                console.log(response); //show object
                this.arraydata = response;
                console.log(this.arraydata);
              },
             (error) => { console.log("Error happened" + error)},
             () => { console.log("the subscription is completed")}
          );
    

答案 1 :(得分:1)

请求异步发生。如果需要操作结果,则移动代码以在回调中使用该数据。

getCards(url)
  {
    this.http.get(url)
              .map(response => response.json())
              .subscribe(
                  function(response) {
                    console.log(response); //show object
                    this.arraydata = response;
                    console.log(this.arraydata)// use it here!
                  },
                  function(error) { console.log("Error happened" + error)},
                  function() { console.log("the subscription is completed")}
              );
  }

许多角度异步发生。这意味着你需要准备等待结果通过使用observables或promises回来。在这种情况下,您可能最好在变量中保存observable,然后您可以在需要使用该值的任何地方订阅observable。

答案 2 :(得分:0)

这是完全正常的。你的http get进行异步调用,它不会等待http.get的响应并在订阅后直接进行并执行console.log()

然后响应将来自服务器,您将影响对arraydata的响应。

我强烈建议您查看javascript中异步工作的方式。

希望它有所帮助。