ng mock服务器数据
Posted Ajanuw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ng mock服务器数据相关的知识,希望对你有一定的参考价值。
安装
yarn add angular-in-memory-web-api -S
src/app/app.module.ts
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
@NgModule({
imports: [
HttpClientModule,
// HttpClientInMemoryWebApiModule模块拦截HTTP请求
//并返回模拟服务器响应。
//当真实服务器准备好接收请求时删除它。
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {
dataEncapsulation: false,
delay: 1500,
}),
],
})
in-memory-data.service
ng generate service InMemoryData
import { Injectable } from "@angular/core";
import { InMemoryDbService } from "angular-in-memory-web-api";
@Injectable({
providedIn: "root",
})
export class InMemoryDataService implements InMemoryDbService {
constructor() {}
createDb() {
const users = [
{ id: 11, name: "Ajanuw" },
{ id: 12, name: "Narco" },
{ id: 13, name: "Bombasto" },
{ id: 14, name: "Celeritas" },
{ id: 15, name: "Magneta" },
{ id: 16, name: "RubberMan" },
{ id: 17, name: "Dynama" },
{ id: 18, name: "Dr IQ" },
{ id: 19, name: "Magma" },
{ id: 20, name: "Tornado" },
];
return { users };
}
}
使用
import { Component } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.styl"],
})
export class AppComponent {
public users: any[] = [];
private heroesUrl = "api/users";
constructor(private http: HttpClient) {}
public getUsers(): void {
this.http.get(this.heroesUrl).subscribe((r: any[]) => {
this.users = r;
});
}
public getUser(id: number): void {
const url = `${this.heroesUrl}/${id}`;
this.http.get(url).subscribe(r => {
console.log(r);
});
}
public getAjanuw(): void {
const url = `${this.heroesUrl}?name=ajanuw`;
this.http.get(url).subscribe(r => {
console.log(r);
});
}
}
html
<ul>
<li *ngFor="let el of users; let i = index">{{ el.name }}</li>
</ul>
<button (click)="getUsers()">get user data.</button>
<hr />
<button (click)="getUser(11)">get user</button>
<hr />
<button (click)="getAjanuw()">get Ajanuw</button
以上是关于ng mock服务器数据的主要内容,如果未能解决你的问题,请参考以下文章
recyclerView.setOnScrollChangeListener 不工作