2017-08-28 36 views
0
login(){ 
    console.log("Test1"); 
    this.authService.login(this.userForm.value) 
     .subscribe(
     response => { 
      console.log("Test2"); 
      console.log(response); 
      if(response === true){ 
      this.router.navigate(['/admin']); 
      }else { 
      this.status = "error"; 
      this.message = "Username or password is incorrect"; 
      } 
     }, 
     error => { 
      console.log(<any>error); 
      this.status = "error"; 
      this.message = error ['message']; 
     } 
    ); 
    } 

Test1將顯示在控制檯中,但Test2不會。看來,訂閱功能從未執行。Angular 4/Laravel .subscribe()將不會執行

函數login()將被我的Angular Form的提交按鈕調用。 如果我提交表單,會出現錯誤。在與.catch線下看...錯誤稱之爲 「服務器錯誤」

login(user: Object): Observable<any>{ 
     return this.http.post('CENSORED LINK TO API', user) 
     .map((response: Response) => { 
      let token = response.json().token; 
      console.log("Response token: " + token); 

      if(token){ 
      this.token = token; 
      localStorage.setItem('token', JSON.stringify(this.token)); 
      return true; 
      } else { 
      return false; 
      } 
     }) 
     .catch((error:any) => Observable.throw(error.json().error || { message: "Server Error"})); 
    } 

here is a picture from the browser

+0

如果你說你得到一個錯誤,它有助於添加關於錯誤的細節到你的問題。 – Markus

+0

錯誤是來自.catch的「服務器錯誤」......請參閱第二個代碼的最後一行。我會編輯它;) –

回答

0

我有finallay答案。

對於具有相同問題的其他人,請將這些行放入laravel api的index.php中。要確保你有

$app = require_once __DIR__.'/../bootstrap/app.php'; 

粘貼此線之上,不要忘記編輯$allowedOrigins,以確保您的POST請求訪問的laravel API的URL。

$allowedOrigins = array(
    '(http(s)://)?angular-elearning-user(\.)?c9users\.io', 
    '(http(s)://)?angular-elearning-user(\.)?c9users\.io(\:)8081', 
    '(http(s)://)?angular-elearning-user(\.)?c9users\.io(\:)8082', 
    'https://localhost:8081', 
    'https://localhost:8082' 
); 

if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != ''){ 
    foreach ($allowedOrigins as $allowedOrigins){ 
     if(preg_match('#' . $allowedOrigins . '#', $_SERVER['HTTP_ORIGIN'])){ 
      header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); 
      header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS'); 
      header('Access-Control-Max-Age: 1000'); 
      header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); 
      break; 
     } 
    } 
} 

並投入Cors.php

public function handle($request, Closure $next) 
{ 
    return $next($request) 
     ->header('Access-Control-Allow-Origin', '*') 
     ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS') 
     ->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token'); 
} 

完蛋了這一點。

如果您仍然有錯誤,請嘗試使用Insomnia或Postman for Google Chrome的表單POST請求。