简体   繁体   中英

Angular2 http.post response undefined

I'm facing problem that I can't win with.

I'm aware of

Make no assumptions about the server API. Not all servers return an object with a data property.

but I simply have no idea how to deal with it. How am I supposed to send data to:

  data => this.exercises.push(data), 

if my response is empty? As a result on a page I recive new li element which is empty. What do I need to do, to see new record without need of page reload?

A little of code:

exercises.component.ts

getExercises() {
  this.exercisesService.getExercises()
    .subscribe(
      exercises => this.exercises = exercises,
      error => this.errorMessage = error);
}

TestPost(){
  let exerciseName = {
    "name": "tetstse"
};

this.exercisesService.addExercise(exerciseName)
  .subscribe(
    data => this.exercises.push(data),
    error => console.log(this.errorMessage),
    () => console.log("Finished properly")
  );

  //this.getExercises();
}

exercises.service.ts

getExercises(): Observable<Exercises[]>{
  return this._http.get(this.getExercisesUrl)
    .map((res: Response) => res.json())
    .catch(this.handleError);
}

addExercise(name): Observable<Exercises> {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  let json = JSON.stringify(name);
  return this._http.post(this.addExerciseUrl, json , headers)
    .map(this.extractData)
    .catch(this.handleError)
}



private handleError (error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.error || JSON.stringify(body);
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Observable.throw(errMsg);
}

private extractData(res: Response) {
  let body = res.json();
  return body.data || { } ;
}

You can check if data is null as shown here:

TestPost() {
        let exerciseName = {
            "name": "tetstse"
        };

        let sub = this.exercisesService.addExercise(exerciseName)
            .subscribe(data => {
             console.log(data);
                if (data != null) {
                    data => this.exercises.push(data) // We have something
                }
                else {
                    console.log('No data returned');
                    // Do something else letting the end user know of this.
                }
            },
            err => {
                console.log('we got an error:', err);
            });

        sub.unsubscribe():
    }

Answer on my question was very simple.

private extractData(res: Response) {
  let body = res.json();
  return body || { } ;
}

body.data || { } ; Wrong

body || { } ; Correct

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