ng4 service服务及Http的使用

创建service


创建服务指令ng g service app

service的代码模仿如下,使用@Injectable类装饰器来装饰

import { Injectable } from '@angular/core';

@Injectable()
export class AppService {
 
  constructor() { }
  
    public test() {
      console.log('first service');
    }

引用service


在Module和component中相对应引入service,如下:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';
import { AppService } from './app.service';



@NgModule({
  declarations: [
    AppComponent,
    FirstComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [AppService],
  bootstrap: [AppComponent]
})
export class AppModule { }

first.component.ts

import { Component } from '@angular/core';
import { AppService } from '../app.service';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  constructor(private service: AppService) {
  }

  ngOnInit() {
    this.service.test();
  }

}

在service中使用Http/HttpClient


  • 在service中引入Http,使用toPromise的方式获取数据。同时需要在app.module.ts中引入HttpModule模块
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

......

constructor(private http: Http, private httpClient: HttpClient) { }

/**
 * 测试toPromise请求数据的方法。
 */
  public testHttp(): any {
    this.http.get('assets/1.json')
    .toPromise()
    .then(response => { console.log(response.json()); })
    .catch(() => { console.log('error'); });
  }
  • 在service中引入HttpClient,这种方法更加便捷。同时需要在app.module.ts中引入HttpClientModule模块
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';
interface TestData {
  id: number;
  name: string;
}
@Injectable()
export class AppService {

  constructor(private httpClient: HttpClient) { }

/**
 * 测试httpClient请求数据的方法。
 */
  public testHttpClient(): any {
    this.httpClient.get('assets/1.json')
    .subscribe(response => { console.log(response.name); }, error => {console.log(error); });
  }
}

  • 还有其他用法可以参考此地址angular中文指南

你可能感兴趣的:(ng4 service服务及Http的使用)