首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在dev期间将虚拟数据插入http post

在dev期间将虚拟数据插入http post
EN

Stack Overflow用户
提问于 2019-04-22 12:08:46
回答 2查看 233关注 0票数 0

我有一个从端点获取数据的方法。

代码语言:javascript
运行
复制
  getManufacturers(): Observable<Manufacturers> {
    const requestBody = { 'num': 12 };

    return this.http.post<Manufacturers>(manufacturersUrl, requestBody).pipe(
      catchError(this.httpErrorService.handleError<Manufacturers>(`getManufacturers`))
    );
   }

端点还没有准备好。我想在虚拟数据中存根,比如:

代码语言:javascript
运行
复制
if(manufacturersUrl === 'dummy-data') {
  return dummyData
}

有两个问题-- 1.我该用什么来包装这些数据?BehaviorSubject.asObserver?2.有没有一种破坏性较小的方法来做到这一点?我可以在不以更优雅的方式更改代码的情况下更改结果吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-22 12:11:13

您只需返回数据

代码语言:javascript
运行
复制
if(manufacturersUrl === 'dummy-data') {
  return of(dummyData)
}
票数 3
EN

Stack Overflow用户

发布于 2019-04-22 12:19:21

使用角的InMemoryWebApi。在内存数据服务中添加虚拟数据.使用它的优点是,一旦实际的API准备好(只需要更改URL),您就不必修改太多的代码。

在应用程序模块中的HttpClientInMemoryWebApiModule之后导入HttpClientModule,以便接收HttpClientModule请求。

代码语言:javascript
运行
复制
@NgModule({
  imports:      [ 
    ...
    HttpClientModule,
    HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService,
    {
      dataEncapsulation: false,
      passThruUnknownUrl: true
    }),
    ...
  ],
  ...
})

您的内存中数据服务将类似于:

代码语言:javascript
运行
复制
import { InMemoryDbService } from 'angular-in-memory-web-api';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 11, name: 'Mr. Nice' },
      { 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 {heroes};
  }
}

你的要求会是:

代码语言:javascript
运行
复制
constructor(private http: HttpClient) { }

getHeroes() {
  return this.http.get('api/heroes') // you just need to change this URL, once your API is ready
}

参见本例:https://stackblitz.com/edit/angular-in-memory-untested-incomplete-mdvl5h?file=src%2Fapp%2Fhero.service.ts

编辑

要调试请求,请在responseInterceptor类中添加一个InMemoryDataService

代码语言:javascript
运行
复制
  responseInterceptor(res: ResponseOptions, ri: RequestInfo) {
      console.log(`response`, res);
      console.log(`request`, ri)
      return res
  }

检查此链接:https://stackblitz.com/edit/angular-in-memory-untested-incomplete-fixlad?file=src%2Fapp%2Fin-memory-data.service.ts

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55794183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档