我正在玩角度2和英雄教程。问题是,无论我打电话给哪个api,我总是得到一个空的对象。
以下是代码:
app.compomnent.ts
import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
// Add the RxJS Observable operators we need in this app.
import './rxjs-operators';
@Component({
selector: 'my-app',
template: `
<h1>Test</h1>
`
})
export class AppComponent implements OnInit {
constructor(private http: Http) {}
private error: any;
ngOnInit() {
var request = this.http.get('http://date.jsontest.com');
console.log("Request: " + request);
console.log("Map: " + request.map(res => res));
console.log("Complete: " + this.http.get('http://date.jsontest.com')
.map(res => res.json())
.catch(this.error));
}
}
main.ts:
// The usual bootstrapping imports
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
HTTP_PROVIDERS
]);
我的控制台中的结果:
答案 0 :(得分:2)
Observable
在您订阅它之前不会做任何事情,因为它们很懒惰
ngOnInit() {
this.http.get('http://date.jsontest.com')
.map(res => res.json())
.subscribe(
data => this.data = data,
() => console.log('done'),
err => this.error(err));
}