通过Angular 2调用服务

时间:2016-11-13 00:52:11

标签: angular

我正尝试在角度2

中使用来自http://jsonplaceholder.typicode.com/posts的服务

我的html如下

employee-information-apps.html
--------------------------------
<button (click)="getDetails()" id="tbn1">Invoke Service</button>

app.ts

//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 {}

但我无法做到这一点。

我犯的错误是什么?

enter image description here

2 个答案:

答案 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 {}

而且,您遗漏了HttpResponse导入。

import {Http, Response} from '@angular/http';

示例Plunker