要使用HttpInterceptor和In memory data service来模拟API调用和数据存储,你可以遵循以下步骤:
-
安装必要的依赖项:
npm install angular-in-memory-web-api --save
-
创建一个模拟数据服务:
// in-memory-data.service.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
return { users };
}
}
-
创建一个HttpInterceptor来拦截HTTP请求并模拟API调用:
// http-interceptor.service.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
// 拦截/users请求,并返回模拟的数据
if (request.url.endsWith('/users') && request.method === 'GET') {
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
return of(new HttpResponse({ status: 200, body: users })).pipe(delay(1000));
}
// 对于其他请求,继续传递给下一个拦截器
return next.handle(request);
}
}
-
在你的Angular模块中注册HttpInterceptor和InMemoryDataService:
// app.module.ts
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { MyHttpInterceptor } from './http-interceptor.service';
@NgModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, { delay: 1000 })
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor, multi: true }
]
})
export class AppModule { }
-
现在你可以在你的组件中使用HttpClient来发起HTTP请求,并且请求会被拦截和处理:
// user.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-user',
template: `
<h2>Users</h2>
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
`
})
export class UserComponent {
users: any[];
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('/users').subscribe((response: any) => {
this.users = response;
});
}
}
现在当你从UserComponent发起GET请求时,它会被HttpInterceptor拦截,并返回模拟的用户数据。你也可以在InMemoryDataService中定义其他的模拟数据和API调用。