我正尝试在角度2
中使用来自http://jsonplaceholder.typicode.com/posts的服务我的html如下
employee-information-apps.html
--------------------------------
<button (click)="getDetails()" id="tbn1">Invoke Service</button>
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { HttpModule } from '@angular/http';
// Annotation section
@Component({
selector: 'my-app',
template: `
<div style="width: 50%; margin: 0 auto;">
<employee-selector></employee-selector>
</div>
`,
})
// Component controller
export class App {
constructor() { }
}
// Annotation section
@Component({
selector: 'employee-selector',
templateUrl: 'employee-information-apps.html'
})
// Component controller
export class EmployeeInformation {
http: Http;
constructor(private _http: Http) {
this.http = http;
this.url='http://jsonplaceholder.typicode.com/posts';
}//end constructor
getDetails(){
return this._http.get(this.url)
.map((response: Response) => Console.log(response.json()))
.catch(this.handleError);
} //end getDetails
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App,EmployeeInformation ],
bootstrap: [ App ]
})
export class AppModule {}
但我无法做到这一点。
我犯的错误是什么?
答案 0 :(得分:1)
你永远不会subscribed
。观察者是冷的&#34;直到用订阅激活。
return this._http.get(this.url)
.map((response: Response) => Console.log(response.json()))
.subscribe(result => {
// this.posts = result;
})
.catch(this.handleError);
答案 1 :(得分:1)
您需要在HttpModule
NgModule
在 app.ts
中@NgModule({
imports: [
BrowserModule,
HttpModule // <--- here!
],
declarations: [ App,EmployeeInformation ],
bootstrap: [ App ]
})
export class AppModule {}
而且,您遗漏了Http
和Response
导入。
import {Http, Response} from '@angular/http';
示例Plunker