我面临的问题是我无法获胜。
我知道
不要假设服务器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 || { } ;
}
答案 0 :(得分:0)
您可以检查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():
}
答案 1 :(得分:0)
回答我的问题非常简单。
private extractData(res: Response) {
let body = res.json();
return body || { } ;
}
body.data || {};的错误的强>
身体|| {}; <强>正确强>