代码之家  ›  专栏  ›  技术社区  ›  obrassard

如何在angular 6中保存http get响应对象

  •  0
  • obrassard  · 技术社区  · 6 年前

    我是angular的新手,我想知道如何将 http.get(url)

    export class AppComponent {
    
      private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
      public data;
    
      constructor(private http: HttpClient) { 
        this.http.get(this.url).subscribe(response => this.data = response);
        console.log(this.data); // -> The result is undefined...
      }
    
    }
    

    一开始,我试着 this.http.get(this.url).subscribe(response => console.log(response)); 这是工作的预期,但分配不起作用。

    谢谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Vlad274    6 年前

    你的密码完全正确。原因是 console.log 未显示响应值是因为它在处理响应之前正在运行。一旦启动了HTTP请求,JavaScript就会继续执行当前函数。

    export class AppComponent {
    
      private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
      public data;
    
      constructor(private http: HttpClient) { 
        this.http.get(this.url).subscribe(response => {
            this.data = response;
            console.log(this.data);
        });
      }    
    }
    
        2
  •  0
  •   Suresh Kumar Ariya    6 年前

    您正在执行异步HTTP调用。所以你需要加上控制台.log内部订阅。

    export class AppComponent {
    
      private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
      public data;
    
      constructor(private http: HttpClient) { 
        this.http.get(this.url).subscribe(response => {
           this.data = response;
           console.log(this.data);
        });
      }