我們使用服務來減少代碼行數量和開發時間。
使採用了棱角分明-CLI命令ng g s Get
一個單獨的服務,這將使得新服務you.but你需要將其添加在這樣app.module.ts提供商。
,或者如果你沒有使用纖維環,CLI使文件get.service.ts文件,請按照下列步驟
入住此示例應用程序,我做。
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { GetService } from './get.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [GetService],
bootstrap: [AppComponent]
})
export class AppModule { }
中get.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class GetService {
constructor(private http: Http) { }
getData() {
this.http.get('https://jsonplaceholder.typicode.com/posts').map(m => m.json()
).subscribe(k => { console.log(k) }); // we have to subscribe for get data out
}
}
app.component.ts應該是這樣的添加這些代碼。
import { Component,Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { GetService } from './get.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(private _service : GetService){
this._service.getData();
}
}
閱讀更多關於服務here
有你在瀏覽器中查看控制檯日誌? – Djamware
@Djamware是的,沒有錯誤 –
更新您的組件和模塊代碼。你希望你的AppComponent可以同時作爲Component和Injectable – Aravind