javascript - 内存中 Web Api 返回 {data : Array[0]}

标签 javascript angular mocking

我正在尝试为我的开发环境获得一些模拟结果。我尝试合并 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。相反,它将相应地创建实体。它的基本行为和默认行为是将数据发送到服务器,与 putdelete 相同。当然,会对 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/

相关文章:

javascript - 嵌套数组的名称

javascript - 将 JSON 提要(WP 提要)解析为 React Native 提要页面

angular - 为什么在 typescript 的 const 中使用带有 ${ 的反勾

objective-c - OCMock,为什么我不能期待协议(protocol)上的方法?

javascript - 按钮不会改变颜色(HTML5)

javascript - 存储多个数据的变量?

angular - 'modal' 不是已知元素 : in angular2

angular - typeof XService 不可分配给类型 'FactoryProvider' 。属性 'provide' 丢失

javascript - 试图模拟 API 响应延迟 : Cannot read property 'then' of undefined

java - 如何在 Java 中模拟 SOAP Web 服务