Issue
good day! I don't understand where my problem. Code in Angular 13 On Form have a Button with submit() procedure
export class RegisterComponent implements OnInit {
 users: User[] = []
 constructor(
    public auth: AuthService
  ) { }
submit() {
this.auth.getByNickName(this.form.value.nickname.trim()).subscribe(
      res => {
       this.users = res
      }
    )
}
}
in AuthService
getByNickName(nickname: string): Observable<User[]> {
    return this.http.get<User[]>(`${environment.fbDbUrl}/users.json`).pipe(
      map((users:User[]) => users.filter((user: User) => user.nickname === nickname))
    )
  }
Result in console: 6402 ERROR TypeError: users.filter is not a function Why? :-(
Solution
The error that you are mentioning 6402 ERROR TypeError: users.filter is not a function tells you that users does not have a method called filter() attached to it.
This is probably because the result of your http.get method is not an array. For example, it might be an object, a null or undefined value.
As you are fetching a .json, is suspect it is an object, not an array (It would have been helpful to have a snippet of that file)
To avoid this error you could either:
- use the optional chaining operator (?.) that will prevent calling the filter method on nullorundefinedvalues:
map((users:User[]) => users?.filter((user: User) => user.nickname === nickname))
- check if your value is an array with the Array.isArray() method.
To solve your issue, as i don't know how what users.json file looks like it is hard to help but assuming it is like:
{
    "users": [
        {
            "id": 1,
            "name": "User1"
        },
        {
            "id": 2,
            "name": "User2"
        }
    ]
}
You would have to modify your map method to reach the users property like this :
map((response: { users: User[] }) => response.users.filter((user: User) => user.nickname === nickname))
Answered By - J. Bosi
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.