2017-01-09 51 views
0

这里是一个authservice登录,采取from here角2 http.post发送空对象

login(email: string, password: string): Observable<boolean> { 
    return this.http.post(
     apiURL + '/admin/login', 
     JSON.stringify({ email: email, password: password })) 
     .map((response: Response) => { 
      // login successful if there's a jwt token in the response 
      let token = response.json() && response.json().token; 
      if (token) { 
       // set token property 
       this.token = token; 

       // store username and jwt token in local storage to keep user logged in between page refreshes 
       localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token })); 

       // return true to indicate successful login 
       return true; 
      } else { 
       // return false to indicate failed login 
       return false; 
      } 
     }); 
} 

在我的部分,我想订阅像这样:

login() { 
    this.loading = true; 
    console.log(this.model); 
    this.authenticationService.login(this.model.email, this.model.password) 
     .subscribe(result => { 
     if(result === true) { 
      this.router.navigate(['/']); 
     } else { 
      this.error = 'Username or password is incorrect'; 
      this.loading = false; 
     } 
     }); 
    } 

我已经做了控制台沿着线路记录以确定数据是否实际传递,并且是。一切检查正常。

除了,发送的数据仅仅是{ }

根据我的快递控制台,这是通过req.body来的唯一的事情。 req.headers表示内容类型是正确的,即,Content-Type: application/json

我试过使用POSTMan向API端点发送相同的json请求。工作正常。

Angular 2的http.post套筒还有另一个诡计吗?

上面的代码有什么问题?

+0

好吧,是数据通过与否?这里有点矛盾。一方面你说数据通过了,另一方面你说的数据只是:'{}':) – Alex

+1

@ AJT_82对于混淆抱歉。我的意思是,一个空对象'{}'是http.post发送的唯一东西。 – Rexford

+0

什么是'this.model'? –

回答

4

在这里发布答案,可能有助于某人。感谢@cartant提供的指针。我只是要看得更近:

  • 我不需要明确设置标题。默认情况下,发送Content-Type: application/json
  • DID不是必须串数据发送。

    login(email: string, password: string): Observable<boolean> { 
    // this is optional 
    // let headers = new Headers({ 'Content-Type': 'application/json' }); 
    // let options = new RequestOptions({ headers: headers }); 
    
    return this.http.post(
        apiURL + '/admin/login', 
        { email: email, password: password }, 
        // options 
        ) 
        .map((response: Response) => { 
         // login successful if there's a jwt token in the response 
         let token = response.json() && response.json().token; 
         if (token) { 
          // set token property 
          this.token = token; 
    
          // store username and jwt token in local storage to keep user logged in between page refreshes 
          localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token })); 
    
          // return true to indicate successful login 
          return true; 
         } else { 
          // return false to indicate failed login 
          return false; 
         } 
        }); 
    }