简体   繁体   中英

Angular4 Typescript; Property 'data' does not exist on type 'any[]'

I am building an app on Angular 4 using TypeScript. I don't know why I get the error

Property 'data' does not exist on type 'any[]'

for an expression like this. I have taken this out of a component;

LoadAllUsers(): void {
    this.AllUsers.Loading = true;
    let AdditionalParams = {
      'page': this.AllUsers.CurrentPage
    };
    this.UserService.All(AdditionalParams)
        .subscribe(
            (users) => {
              this.AllUsers.Users = users.data;
              this.AllUsers.Data = users;
              this.AllUsers.Loading = false;
              this.AllUsers.Loaded = true;
              console.log ("Users response: ", this.AllUsers, this.AllUsers.Users);
            },
            (error)=>  {
              this.AllUsers.Loading = false;
              console.log ("THE ERROR: ", error);
              this.AllUsers.RequestStatus = error.status=0;
              if (typeof error.json == 'function' && error.status!=0) {
                let errorObject = error.json();
                this.AllUsers.RequestError = errorObject;
              } else {
                this.AllUsers.RequestError = "net::ERR_CONNECTION_REFUSED";
              }
              this.AllUsers.HasRequestError = true;
            });
  }

I can only bypass this error by using; (users) => this.PrepareUsers(users)

I must be missing something about TypeScript. What's strange is I can use error.status

I'm guessing you should change the method signature in your service to something like All(AdditionalParams: any): Observable<User[]> , of course, that is if you do have an User model. Also, variables and methods should start with lower case.

The data being returned from your service in the (users) parameter is an array. All arrays have the same properties and methods. .data is not a property or method of an array.

You can find all the properties and methods on the Array type here

Something that may help you debug your specific problem would be to log the (users) to the console and see what the data looks like:

LoadAllUsers(): void {
    this.UserService.All(AdditionalParams)
        .subscribe(
            (users) => {
              console.log(users);
            });
  }

Your data might not be coming back to you in the form that you're expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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