请帮助我理解并修复此错误:
我正在尝试从本地服务器获取数据,结果我在控制台中看到此错误:
ERROR TypeError: Cannot read property 'json' of undefined
(“Postman”和浏览器正确地向我显示响应)
完整错误:Screeshot console error
我使用 Angular 4.3.1
我的代码如下所示:
服务
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http, RequestOptionsArgs, Response} from '@angular/http';
import {ResponseContentType} from '@angular/http/src/enums';
export class User {
constructor(public id: number,
public name: string,
public age: number,
public occupation: string) {
}
}
@Injectable()
export class UserService {
private userUrl = 'http://localhost:8000/api/v1/';
constructor(private http: Http) {
}
getUsers(name?: string): Observable<User[]> {
return this.http.get(`${this.userUrl}users`, {params: {name}})
.map((res: Response) => { return res.json() })
.catch((error: any) => Observable.throw(error.json().error ||
'Server error'));
}
组件
import 'rxjs/add/operator/switchMap';
import {Observable} from 'rxjs/Observable';
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, ParamMap} from '@angular/router';
import {User, UserService} from './user.service';
import {FormControl} from '@angular/forms';
@Component({
templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {
users: Observable<User[]>;
public search: FormControl = new FormControl();
constructor(private service: UserService) {
}
ngOnInit() {
this.users = this.search.valueChanges
.startWith('')
.debounceTime(800)
.distinctUntilChanged()
.switchMap(name => this.service.getUsers(name));
}
}
最佳答案
从屏幕截图中可以看出,您在从服务器检索数据时遇到了一些问题。因此,您陷入了 catch 分支并尝试对空错误执行 json 操作。
检查您的服务器以及为什么在调用失败时它没有返回错误。这可能会告诉您为什么 API 调用不起作用的线索。
但是根据您最初的问题,这与可观察的成功分支中的响应无关。你的代码是正确的。您必须找出 API 调用失败的原因。
编辑
仔细一看,我发现您的请求格式不正确,您应该执行类似的操作
getUsers(name?: string): Observable<User[]> {
let myParams = new URLSearchParams();
myParams.append('name', name);
let options = new RequestOptions({ params: myParams });
return this.http.get(`${this.userUrl}users`, options)
.map((res: Response) => { return res.json() })
.catch((error: any) => Observable.throw(error.json().error ||
'Server error'));
}
关于javascript - 错误类型错误: Cannot read property 'json' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47858642/