2017-03-17 17 views
0

我正在開發一個angular2作爲前端的應用程序我想從客戶端登錄到服務器端,但是當我嘗試傳遞憑據時,我在瀏覽器控制檯中出現了這些錯誤。Angular2:data.json不是函數

在運行時,它抱怨有:

data.json is not a function

這是我的服務代碼:

import { Injectable } from '@angular/core'; 

import { Http, Response, Headers } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class LoginService { 
isAuthenticated: boolean = true; 

    constructor(private http: Http) { 

    } 

    login(username: string, password: string) { 
    const headers = new Headers(); 

    const creds = 'username=' + username + '&password=' + password; 

    headers.append('Authorization', 'Basic ' + btoa(username + ':' + password)); 

    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 

    return new Promise((resolve) => { 

     this.http.post('http://localhost:8080/StudentManager/login', creds, { headers: headers }) 

     .map(this.extractData) 

     .subscribe(
      (data) => { 
        if(data.json().success) { 
       window.localStorage.setItem('auth_key', data.json().token); 
       console.log(username); 
       this.isAuthenticated = true; 
        } 
       resolve(this.isAuthenticated); 
      }); 

    } 
    ); 
    } 

} 

以下是錯誤的快照:

enter image description here

回答

2

data代替data.json(),因爲你已經在使用extractData

.subscribe(
     (data) => { 
      if(data.success) { 
       window.localStorage.setItem('auth_key', data.token); 
       console.log(username); 
       this.isAuthenticated = true; 
      } 
      resolve(this.isAuthenticated); 
     }); 
+0

它的工作,錯誤消失了,但我不知道爲什麼你的映射數據JSON它不會進入'if(data.success)'裏面,即使我把正確的憑證 – SuperGirl

+0

檢查'data.success'的值 –

0

您的問題在你的數據對象中沒有功能json()克拉。更改爲

.subscribe(
      (data) => {   
       window.localStorage.setItem('auth_key', data.json().token); 
       console.log(username); 
       this.isAuthenticated = true;      
       resolve(this.isAuthenticated); 
      }); 

你也不必對數據執行方法內部的檢查,因爲如果你是這裏面的要求是成功的,否則它會去的錯誤。

0

你可以試試這個

this.http.post('http://localhost:8080/StudentManager/login', creds, { headers: headers }) 
     .map(res => res.json()) 
     .subscribe(
      (data) => { 
        if(data.success) { 
          .... 
        } 
      }); 

    } 
相關問題