我正在使用 Angular 2 发出返回 JSON 的 HTTP 请求,然后我用它来填充对象的属性。 URL 根据我传递给调用 http.get 方法的函数的用户名而变化。显然,当我将数据库中不存在的用户名传递给函数时,它会抛出 404 错误。
这是 http 调用:
getUser(un: string):Observable<TwitchUser> {
return this.http.get('https://api.twitch.tv/kraken/channels/' + un, { headers: this.getHeaders() })
.map(r=>{
let body = r.json();
var user:TwitchUser = {
name: un,
displayName: body.display_name,
status: body.status,
logo: body.logo,
isOnline: false,
url: body.url
};
return user;
})
.catch(this.handleError);
}
我想做的是,当抛出 404 错误时,为丢失的用户帐户构建一个“占位符”对象。
类似这样的事情:
var user:TwitchUser = {
name: un,
displayName: un,
status: 'No active account found for this user!',
logo: 'http://hotchillitri.co.uk/wp-content/uploads/2016/10/empty-avatar.jpg',
isOnline: false,
url: ''
};
但是,我不知道如何使用 Angular 2 实现这一点。有人可以帮助我吗?
谢谢!
更新:
我尝试了下面答案中的方法#1:
.catch((error: any):Observable<TwitchUser> => {
var user: TwitchUser = {
name: un,
displayName: un,
status: 'No active account found for this user!',
logo: 'http://hotchillitri.co.uk/wp-content/uploads/2016/10/empty-avatar.jpg',
isOnline: false,
url: ''
};
return user;
}
但是我在第一行收到此错误:
Argument of type '(error: any) => TwitchUser' is not assignable to parameter of type '(err: any, caught: Observable<TwitchUser>) => ObservableInput<{}>'.
Type 'TwitchUser' is not assignable to type 'ObservableInput<{}>'.
Type 'TwitchUser' is not assignable to type 'ArrayLike<{}>'.
Property 'length' is missing in type 'TwitchUser'.
我尝试了下面答案中的方法#2:
ngOnInit() {
let userNames: string[] = this.service.getUsernames();
for (var i = 0; i < userNames.length; i++) {
this.service.getUser(userNames[i])
.subscribe(u => {
this.service.getUserIsOnline(u.name).subscribe(val => {
u.isOnline = val;
this.users[this.users.length] = u;
if(this.users.length == userNames.length){
this.changeMode(0);
}
});
}
, (error) => {
console.log("an error occurred! Username is " + userNames[i])
}
, () => {
console.log("inside the 'final' block. Username is " + userNames[i])
}
);
}
}
但我无法确定哪个用户名导致了问题,因为 catch 和 finally block 仅执行一次(当我记录它时,i = userNames.length)。
最佳答案
您可以在 .catch() 中指定要返回错误消息或“占位符”对象的内容,如上所述。
.catch((error: any) => {
// you can return error
return (Observable.throw(error.json()))
}
})
或者您可以重新运行占位符对象,这完全取决于您的要求
.catch((error: any) => {
// you can return error
var user:TwitchUser = {
name: un,
displayName: body.display_name,
status: body.status,
logo: body.logo,
isOnline: false,
url: body.url
};
return user;
}
})
并且您可以从使用服务的位置捕获错误 block 中的错误响应
.subscribe((result) => {
console.log(result)
}
, (error) => {
// you can catch error response in this block
console.log(error)
}
, () => {
//finally block, always executes
}
);
关于javascript - 当使用 Angular 2 进行 HTTP 调用失败并出现 404 错误时,如何构建占位符对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233303/