我们使用服务来减少代码行数量和开发时间。
使采用了棱角分明-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