1

With Angular 5 deprecating Http and HttpModule in favor of HttpClient and HttpClientModule, I haven't been able to figure out how to pass session tokens around similar to how I used to. For example, this is how I used to do it:

loginUser(loginData) {
    this.http.post('http://localhost:3000/login', loginData).subscribe(res => {
      localStorage.setItem('token', res.json().token);
    })
  }

Now that json is the assumed default, how would I do something similar to "res.json().token"? The closest I have found is to use "JSON.stringify", but the problem is it passes the entire json object into the header, not just the token itself. ie;

loginUser(loginData) {
    this.http.post('http://localhost:3000/login', loginData).subscribe(res => {
      localStorage.setItem('token', JSON.stringify(res));
    })
  }
Clark Brent
  • 189
  • 1
  • 10
  • 2
    `localStorage.setItem('token', res.token)` ? – AT82 Nov 25 '17 at 10:37
  • 1
    just omit `.json()` part – Bohdan Khodakivskyi Nov 25 '17 at 11:08
  • I tried omitting .json() early on, but it errors with a "Property token does not exist on type 'Object'." – Clark Brent Nov 25 '17 at 11:54
  • Yep, you're absolutely right, @AJT_82. Bravo and thanks! I was actually just explicitly adding an interface inline like so: loginUser(loginData) { this.http.post('http://localhost:3000/login', loginData).subscribe((res: {token: string}) => { localStorage.setItem('token', res.token); }) } – Clark Brent Nov 25 '17 at 12:54

0 Answers0