2016-10-23 23 views
15

Cách chính xác để lấy dữ liệu json từ http nhận được trong Angular 2. Tôi đang thử nghiệm một số dữ liệu cục bộ với điểm cuối giả định và tôi có thể xem kết quả trong số http.get() nhưng tôi không thể gán nó cục bộ hoặc có một số vấn đề về thời gian. Đây là dịch vụ đơn giản của tôi:Góc 2 Http Nhận trả lời Ví dụ

import {Injectable} from '@angular/core'; 
import {Http} from '@angular/http'; 
import 'rxjs/add/operator/map'; // we need to import this now 

    @Injectable() 
    export class MyHttpService { 
    constructor(private _http:Http) {} 

    getDataObservable(url:string) { 
     return this._http.get(url) 
      .map(data => { 
       data.json(); 
       console.log("I CAN SEE DATA HERE: ", data.json()); 
     }); 
    } 
} 

Và đây là làm thế nào tôi đang cố gắng để gán dữ liệu:

import {Component, ViewChild} from "@angular/core"; 

import { MyHttpService } from '../../services/http.service'; 

@Component({ 
    selector: "app", 
    template: require<any>("./app.component.html"), 
    styles: [ 
     require<any>("./app.component.less") 
    ], 
    providers: [] 
}) 
export class AppComponent implements OnInit, AfterViewInit { 
    private dataUrl = 'http://localhost:3000/testData'; // URL to web api 
    testResponse: any; 

    constructor(private myHttp: MyHttpService) { 
    } 

    ngOnInit() { 
     this.myHttp.getDataObservable(this.dataUrl).subscribe(
      data => this.testResponse = data 
     ); 
     console.log("I CANT SEE DATA HERE: ", this.testResponse); 
    } 
} 

tôi có thể xem dữ liệu tôi muốn trong get() gọi nhưng tôi don' t dường như có quyền truy cập vào nó sau cuộc gọi đó ... xin vui lòng cho tôi biết những gì tôi đang làm sai!

+0

Đó là toàn bộ điểm gọi lại để đăng ký. – jonrsharpe

Trả lời

13

Điều đó không được phép hoạt động theo cách này. Khi dữ liệu đến cuộc gọi lại được truyền đến quan sát được gọi. Mã cần truy cập dữ liệu này phải nằm trong phần gọi lại.

ngOnInit() { 
    this.myHttp.getDataObservable(this.dataUrl).subscribe(
     data => { 
      this.testResponse = data; 
      console.log("I CANT SEE DATA HERE: ", this.testResponse); 
     } 
    ); 
} 

cập nhật

getDataObservable(url:string) { 
    return this._http.get(url) 
     .map(data => { 
      data.json(); 
      // the console.log(...) line prevents your code from working 
      // either remove it or add the line below (return ...) 
      console.log("I CAN SEE DATA HERE: ", data.json()); 
      return data.json(); 
    }); 
} 
+0

Ok, cảm ơn bạn đã giải thích tôi vẫn còn mới với Angular và cách thực hiện đúng các cuộc gọi http. Điều đó đang được nói, nếu tôi xử lý dữ liệu trong hàm gọi lại như bạn hiển thị ở trên, tôi vẫn thấy: – DHW

+1

'TÔI CẦN XEM DỮ LIỆU TẠI ĐÂY: undefined' – DHW

+0

Chức năng' map (...) ´ cần trả về giá trị, nếu không người đăng ký sẽ không nhận được gì. Nếu 'bạn loại bỏ dòng' console.log ... ',' data.json() 'sẽ trả về kết quả. –

5

Bởi vì cuộc gọi http là async. Bạn cần phải thực hiện các bài tập trong chức năng đăng ký. Thử cách này:

this.myHttp.getDataObservable(this.dataUrl).subscribe(
      data => { 
         this.testResponse = data ; 
         console.log("I SEE DATA HERE: ", this.testResponse); 
        } 
     ); 
+1

Cách sử dụng this.testResponse trong trang .html? {{testResponse}} hiển thị dưới dạng đối tượng trống. – arjun

1

Đây là mẫu dễ sử dụng cho phép bạn sử dụng lời hứa.

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { Config } from '../Config'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/Rx'; 

@Injectable() 
export class Request { 

    constructor(public http: Http) 
    { 

    } 

    get(url): Promise<any> 
    { 
     return this.http.get(Config.baseUrl + url).map(response => { 
      return response.json() || {success: false, message: "No response from server"}; 
     }).catch((error: Response | any) => { 
      return Observable.throw(error.json()); 
     }).toPromise(); 
    } 

    post(url, data): Promise<any> 
    { 
     return this.http.post(Config.baseUrl + url, data).map(response => { 
      return response.json() || {success: false, message: "No response from server"}; 
     }).catch((error: Response | any) => { 
      return Observable.throw(error.json()); 
     }).toPromise(); 
    } 
} 
Các vấn đề liên quan