O
O
Oleg Voitenko2018-04-30 14:44:31
Angular
Oleg Voitenko, 2018-04-30 14:44:31

Why doesn't map work in Angular 4?

Good afternoon!
Can't figure out why the content of response.json() is empty in Angular4 (Angular CLI). Tell me, where is the joint?
The code is the following:

import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
import {HttpClient, HttpHeaders} from "@angular/common/http";


@Injectable()
export class AuthenticationService {
    public token: string;

    constructor(private http: HttpClient) {
        var currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;

    }
login(username: string, password: string): Observable<boolean> {
        return this.http.post('http://apiserver.com/api/v1/login', JSON.stringify({ username: username, password: password })
            .map((response: Response) => {
            var token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;
                localStorage.setItem('currentUser', JSON.stringify({username: username, currentUser: token}));
                return true;
            } else {
                return false;
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew K., 2018-04-30
@OliverV

HttpClient does not need to use json()
var token = response && response.token

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question