Angular中的Ajax


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/12/05/Angular%E4%B8%AD%E7%9A%84Ajax/

摘要

本文主要讲述了:

  1. 反向代理
  2. 发起请求

正文

注意:使用 Ajax 需要在根模块引用HttpClientModule模块

示例:

my-angular/src/app/app.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FooComponent } from './pages/foo/foo.component';
import { BarComponent } from './pages/bar/bar.component';

import { RegisterModule } from './modules/register/register.module';

import { SalaryPipe } from './pipes/salary.pipe';
import { IsVipPipe } from './pipes/is-vip.pipe';

@NgModule({
declarations: [
AppComponent,
FooComponent,
BarComponent,
SalaryPipe,
IsVipPipe,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
AppRoutingModule,
RegisterModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

反向代理

示例:

my-angular/angular.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "my-angular:build:production"
},
"development": {
"browserTarget": "my-angular:build:development",
"proxyConfig": "src/proxy.conf.json"
}
},
"defaultConfiguration": "development"
}
}

my-angular/src/proxy.conf.json

1
2
3
4
5
{
"/api": {
"target": "http://localhost:3000"
}
}

/api/getList -> http://localhost:3000/api/getList

发起请求

HttpClient注入服务,在服务中发起 Ajax 请求

GET

示例:

my-angular/src/app/app.component.html

1
2
3
4
5
6
7
<div *ngFor="let item of jobList; trackBy: jobTrackBy">
<div>{{ item.jobId }}</div>
<div>{{ item.jobName }}</div>
<div>{{ item.salary }}</div>
<div>{{ item.companyName }}</div>
</div>
<button (click)="getJobList()">Get Job List</button>

my-angular/src/app/app.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Component } from '@angular/core';
import { Job } from './types/Job';
import { JobsService } from './services/jobs.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
jobList: Job[] = [];

jobTrackBy(index: number, item: Job) {
return item.jobId;
}

getJobList() {
this.jobService.getList().subscribe((list: Job[]) => {
console.log(list);
this.jobList = list;
});
}

constructor(private jobService: JobsService) {}
}

my-angular/src/app/services/jobs.service.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Injectable } from '@angular/core';
import { Job } from '../types/Job';

import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
providedIn: 'root',
})
export class JobsService {
getList(): Observable<Job[]> {
return this.http.get<Job[]>('http://a.example.com/job.json').pipe(
catchError(function (error) {
console.log(error);
return of([]);
})
);
}

constructor(private http: HttpClient) {}
}

a.example.com/job.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[
{
"jobId": 1,
"jobName": "会计",
"salary": 1000,
"companyName": "A有限责任公司",
"isVip": 1
},
{
"jobId": 2,
"jobName": "销售",
"salary": 2000,
"companyName": "B有限责任公司",
"isVip": 0
},
{
"jobId": 3,
"jobName": "主管",
"salary": 3000,
"companyName": "B有限责任公司",
"isVip": 0
}
]

POST

示例:Content-Type: application/json

my-angular/src/app/services/jobs.service.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Injectable } from '@angular/core';
import { Job } from '../types/Job';

import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
providedIn: 'root',
})
export class JobsService {
getList(): Observable<Job[]> {
return this.http
.post<Job[]>('http://a.example.com/job.json', {
a: 1,
b: 2,
})
.pipe(
catchError(function (error) {
console.log(error);
return of([]);
})
);
}

constructor(private http: HttpClient) {}
}

示例:Content-Type: application/x-www-form-urlencoded

my-angular/src/app/services/jobs.service.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Injectable } from '@angular/core';
import { Job } from '../types/Job';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
providedIn: 'root',
})
export class JobsService {
getList(): Observable<Job[]> {
return this.http
.post<Job[]>('http://a.example.com/job.json', 'a=1&b=2', {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
}),
})
.pipe(
catchError(function (error) {
console.log(error);
return of([]);
})
);
}

constructor(private http: HttpClient) {}
}

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/12/05/Angular%E4%B8%AD%E7%9A%84Ajax/


本文对你有帮助?请支持我


支付宝
微信