Jhosef
Jhosef

Reputation: 47

InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' ERROR

I have a problem with a service a developed to consume some data from my database, when i try to visualize the data on the HTML:

JSON on Postman:

{
    "error": false,
    "data": [
        {
            "id": 1,
            "name": "Jhosef ",
            "surname": "Cadich",
            "email": "[email protected]",
            "password": "aaaa",
            "role": 1,
            "USERcol": "1",
            "SHOP_id": 1
        }
    ]
}

Service:

export class UserService {

  apiUrl='http://localhost:3000/api/user/';
  

  constructor(private _http: HttpClient) { 
    console.log('User service running');
  }


getApiUsers(){
  console.log(this._http.get<any[]>(this.apiUrl));
  return this._http.get<any[]>(this.apiUrl);
}
}

Component where I want to use the service:

export class AdminComponent implements OnInit {

  users$:any[];

  constructor(private userService: UserService) { 
    this.admim_user$ = userService.getUsers();
  }

  ngOnInit() {
    return this.userService.getApiUsers().subscribe(data =>this.users$ = data);
  }

}
`

on HTML

    <li class="list-group-item" *ngFor="let index of (users$ | async)?.data">
        <h6>Email-api:{{index.email}}</h6>
    </li>

Thank you very much for your Help!!!

Upvotes: -1

Views: 5369

Answers (1)

Sherif Elmetainy
Sherif Elmetainy

Reputation: 4502

You are already subscribing to the observable returned by the service. users$ is not an observable.

You can either change you typescript code to

users$: Observable<any[]>
....
this.users$ = this.userService.getApiUsers();

Here there is no need to subscribe, since this is basically what the async pipe does.

Another alternative is not using async pipe and relying on subscribe. This is particularly useful in case you want to do some extra processing with the users in the typescript code, or if users list is needed in multiple place in the HTML since every subscribe will issue a new HTTP request.

users: any[]
this.userService.getApiUsers().subscribe(data =>this.users$ = data);

And in HTML

<li class="list-group-item" *ngFor="let user of users?.data">
    <h6>Email-api:{{user.email}}</h6>
</li>

Note that I changed the property name in the second case to users since $ is a convention for naming observables.

Also I changed let index to let user since index is usually the a counter 0, 1, 2, 3, etc. Better not use it for another purpose when the actual value is a user object.

Upvotes: 1

Related Questions