简体   繁体   English

错误TypeError:无法读取未定义的属性'json'

[英]ERROR TypeError: Cannot read property 'json' of undefined

Help me please understand and fix this error: 帮我,请理解并解决此错误:

I'm trying to get data from the local server and as a result I see this error in the console: 我试图从本地服务器获取数据,结果在控制台中看到此错误:

ERROR TypeError: Cannot read property 'json' of undefined

("Postman" and the browser get and show me the response correctly) (“邮递员”和浏览器会正确显示并显示响应)
The full err: Screeshot console error 完全错误: Screeshot控制台错误
I use Angular 4.3.1 我使用Angular 4.3.1

My code looks like this: 我的代码如下所示:

SERVICE 服务

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'));
}

COMPONENT 零件

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

From what I can see in the screenshot you're having some issue retrieving the data from the server. 从我在屏幕截图中可以看到的,您在从服务器检索数据时遇到了一些问题。 Due to this you're falling into the catch branch and trying to do a json on an empty error. 因此,您陷入了catch分支,并试图在一个空错误上执行json。

Check your server and why it's not returning an error when the call is failing. 检查您的服务器以及调用失败后为什么它不返回错误。 That might give you a clue why the call on the API is not working. 这可能会为您提供线索,说明为什么对API的调用无法正常工作。

But as per your initial question this has nothing to do with the response in the success branch of the observable. 但是,按照您最初提出的问题,这与可观察对象的成功分支中的响应无关。 Your code is correct. 您的代码是正确的。 You have to figure out why the call to your API is failing. 您必须弄清楚为什么对您的API的调用失败。

Edit 编辑

On a closer look I noticed that your request is not in the proper format you should be doing something like 仔细观察,我发现您的请求格式不正确,您应该执行以下操作

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'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM