簡體   English   中英

Angular2 http.post響應未定義

[英]Angular2 http.post response undefined

我面臨着無法解決的問題。

我知道

不假設服務器API。 並非所有服務器都返回帶有數據屬性的對象。

但我根本不知道如何處理。 我應該如何將數據發送到:

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

如果我的回答是空的? 結果,在頁面上,我收到了新的li元素,該元素為空。 我需要怎么做才能查看新記錄而無需重新加載頁面?

一些代碼:

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 || { } ;
}

您可以檢查data是否為空,如下所示:

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():
    }

我的問題的答案很簡單。

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

body.data || {}; 錯誤

身體|| {}; 正確

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM