简体   繁体   中英

Angular 5 InMemoryWebAPI - How to simulate CRUD with HTTP Verbs?

In working with the Angular docs / tutorial on the in-memory web api , I want to return some JSON values that indicate the success or failure of a request. ie:

{success:true, error:""}

or

{success:false, error:"Database error"}

But, the code in the example for the in-memory-data.service.ts file only has the one method: createDb() .

How do update that service code to respond to a PUT/POST/DELETE request differently than a GET?

Note : In real-life / production, the backend will be PHP, and we can return these values any way we want (with the correct status codes). This question is specifically directed at making the In Memory Web API mock those responses.

Example:

Executing:

return = this.http.post(url,someJsonData,httpHeaders);

I would want return to be: {success:'true',id:1234} with an HTTP Status code of 200.

Later, to delete that record that was just created:

url = `/foo/` + id + '/'; // url = '/foo/1234/';
this.http.delete(url);

This wouldn't really need a JSON meta data response. An HTTP Status code of 200 is sufficient.

How do update that service code to respond to a PUT/POST/DELETE request differently than a GET?

The server will always respond to the requests that you have made. So if you fire an Ajax request it may be one of the known HTTP Methods (like POST, GET, PUT...). Afterwards you'll wait for the answer.

/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

/** GET: get a new hero from the database */
getHero (heroId: number): Observable<Hero> {
  return this.http.get(this.heroesUrl + '/' + heroId)
}

I found the answer I was looking for: It's HttpInterceptors.

This blog post and the corresponding github repo demonstrate exactly how to simulate CRUD operations in Angular 2/5 without having to setup a testing server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM