我正在尝试为我的开发环境获得一些模拟的结果。我试图在没有太大成功的情况下将Angular-In-In-inmory-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 {
模拟 - event.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.'));
}
}
模拟 - 事实data.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。但是,无论出于何种原因,/事件的POST
总是返回{data: Array[0]}
。
提供的任何帮助将不胜感激。
谢谢!
post
方法不仅会将数据检索到 angular-in-memory-web-api
。相反,它将相应地创建实体。这是必不可少的,默认行为是将数据发送到与put
和delete
相同的服务器。当然,对邮政请求的响应可能是angular-in-memory-web-api
情况下的数据,但请记住,这完全取决于服务器的响应。在另一个get
上,应根据需要从angular-in-memory-web-api
检索数据。
好吧,事实证明,POST
似乎在angular-in-memory-web-api
中返回数据。我通过使用GET
请求成功检索数据。这不是理想的,但是现在必须工作。
如果某人有更好的答案,请提供它,因为提交不使用原始请求类型的模拟有点。
谢谢!