每天学习一点点,成功增加一大步

Angular笔记:HTTP 服务

Angular zhanghui 303℃

Angular 的 HTTP 服务相比之前的学习会比较的轻松,它和 Jquery 的 Ajax 服务、AngularJS 的 Http 服务等的使用相类似。所以你如果之前有使用上两种的话学习这个就不难,接着写下几个关键性的步骤。

1、必须是在 AppModule 中必须要引入 HttpModule。

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


import {AppComponent} from './app.component';
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {PostComponent} from './post/post.component';
import {GetComponent} from './get/get.component';

@NgModule({
  declarations: [
    AppComponent,
    PostComponent,
    GetComponent,
  ],
  imports: [
    BrowserModule, FormsModule, HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

2、GET 请求

import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Http} from "@angular/http";

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

  private dataMaps: Observable<any>;
  private resInfo: any;

  constructor(public http: Http) {
    let url = '';
    this.dataMaps = this.http.get(url).map(res => res.json());
  }

  ngOnInit() {
    this.dataMaps.subscribe(
      data => {
        this.resInfo = data;
        console.log('GetComponent:');
        console.log(this.resInfo);
      }
    );
  }

}

3、POST 请求

import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs";
import {Headers, Http} from "@angular/http";
import "rxjs/Rx";

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

  private mobile: number = 13812345678;
  private code: number = 123456;
  private dataMaps: Observable<any>;
  private resInfo: any;
  private url: string;
  private parmas: string;

  constructor(public http: Http) {
    let myHeaders: Headers = new Headers();
    myHeaders.append('Content-Type', 'application/json');
    this.url = '';
    this.parmas = JSON.stringify({
      Data: JSON.stringify({mobile: this.mobile, authCode: this.code}),
      Token: '', Sign: ''
    });
    this.dataMaps = this.http.post(this.url, this.parmas, {headers: myHeaders}).map(res => res.json());
  }

  ngOnInit() {
    this.dataMaps.subscribe(
      data => {
        this.resInfo = data;
        console.log('PostComponent');
        console.log(this.resInfo);
      }
    );
  }

}

GET 和 POST 是常用的两种请求方式,所以这里只演示这两种,当然还有 Angular 其他的请求方式,它们的写法相似。

更多的请参考:https://angular.cn/tutorial/toh-pt6

转载请注明:隨習筆記 » Angular笔记:HTTP 服务