Z
Z
zlodiak2018-07-02 23:24:58
JavaScript
zlodiak, 2018-07-02 23:24:58

Why doesn't JSON.parse eat the string?

I request an object from the backend like this:
service:

@Injectable()
export class UserService {

  constructor(private httpClient: HttpClient) { }

  authUser(login) {
    return this.httpClient.get(Config.host + 'users/get_user?login=' + login);
  }

}

Click handler in component:
submit() {
    const login = this.form.controls.login.value;
    this.userService.authUser(login).subscribe(user => {
      console.log(typeof user, user)
      console.log(JSON.parse(user));
    });
  }

As a result, the type of response and the response are displayed in the console:
string [{"model": "app_users.user", "pk": 1, "fields": {"login": "[email protected]", "fname": "kalinin", "lname": "sergey"}}]

It can be seen that in the handler I wrap the response in JSON.parse () so that in the future it will be possible to work with the response as an array. But the console gives the following error:
webpack: Compiled successfully.
ERROR in src/app/components/login/login.component.ts(27,30): error TS2345: Argument of type 'Object' is not assignable to parameter of type 'string'.

Please tell me how to fix the situation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2018-07-02
@zlodiak

This error is not a runtime error, but a compilation error. Watch the types. Try this console.log(JSON.parse(user)); replaced by
console.log(JSON.parse(user.toString()));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question