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!
Đó là toàn bộ điểm gọi lại để đăng ký. – jonrsharpe