我正在尝试为我的开发环境获得一些模拟结果。我尝试合并 angular-in-memory-web-api没有取得多大成功。这是我的代码:
app.module.ts:
@NgModule({
declarations: [
AppComponent,
],
imports: [
...
HttpModule,
...
InMemoryWebApiModule.forRoot(MockEventData, {
passThruUnknownUrl: true
})
],
providers: [
...
{
provide: Http,
useClass: ExtendedHttpService
},
...
{
provide: EventService,
useFactory: (http: Http, userService: UserService, newEventService: NewEventService, router: Router) => {
if (environment.production) {
return new EventService(http, userService, newEventService, router)
} else {
return new MockEventService(http, userService, newEventService, router)
}
},
deps: [Http, UserService, NewEventService, Router]
}
],
bootstrap: [AppComponent]
})
export class AppModule {
模拟事件.service.ts:
@Injectable()
export class MockEventService {
private imageUploadBatch: Observable<Boolean>[];
private fakeResponse;
constructor(
private http: Http,
private userService: UserService,
private newEventService: NewEventService,
private router: Router,
) {
};
getEvents(excludedEvents: string[]): Observable<Event[]> {
return this.http
.post('api/events', excludedEvents)
.map((res: Response) => res.json())
.publishLast().refCount()
.catch((error: any) => Observable.throw(error.json().error || 'Show error.'));
}
}
模拟事件数据.ts:
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class MockEventData implements InMemoryDbService {
createDb() {
let events = [
{ id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' },
{ id: 4, name: 'Tornado' }
];
return { events };
}
}
代码非常简单。我按照本指南制作的:https://angular.io/docs/ts/latest/guide/server-communication.html 。但是,无论出于何种原因,/events 的 POST
始终返回 {data: Array[0]}
。
我们将深深感谢您提供的任何帮助。
谢谢!
最佳答案
post
方法不仅仅将数据检索到 angular-in-memory-web-api
。相反,它将相应地创建实体。它的基本行为和默认行为是将数据发送到服务器,与 put
和 delete
相同。当然,会对 post 请求做出响应,这可能是 angular-in-memory-web-api 情况下的数据,但请记住,这完全取决于服务器的响应。另一方面,get
应该用于根据需要从 angular-in-memory-web-api
检索数据。
关于javascript - 内存中 Web Api 返回 {data : Array[0]},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42812701/