2017-07-18 28 views
1
import {Component, OnInit} from '@angular/core'; 
import {LoginService} from "../../services/login.service"; 
import {LoginUser} from "../../services/model"; 

@Component({ 
selector: 'login-component', 
templateUrl: './login.component.html', 
styleUrls: ['./login.component.css'] 
}) 

export class LoginComponent implements OnInit { 
private user: LoginUser = new LoginUser(); 
public flag : boolean = false; 
constructor(private loginService: LoginService) {} 

login(): void { 
    this.flag = true; 
    this.loginService.login(this.user).then(function (response) { 
    console.log(this.flag); 
    }); 
} 
} 

我無法在登錄服務調用的響應中訪問或分配變量值。但是,我可以在登錄方法中將其更新爲true。 我在登錄服務中也面臨同樣的問題。如何在angular4中的同一類中聲明的服務響應中訪問變量?

回答

0

綁定(這個)可能會幫助你解決你的問題。

login(): void { 
    this.flag = true; 
    this.loginService.login(this.user).then((response)=>{ 
     console.log(this.flag); 
    }); 
} } 
+0

我們不能用ES6並結合共同發揮作用。我們也可以使用綁定函數來解決它。雖然,通過使用下面的方式。 login():void { this.flag = true; (this.user).then(function(){ console.log(this.flag); } .bind(this)); } – Darpan

+0

瞭解。不需要使用bind(this)。 Angular使用打字稿。 @CozyAzure已經回答了。更新了我的答案。 – 2017-07-20 05:09:16

1

Angular使用Typescript默認情況下具有大部分ES6功能。如果您想要作爲回調參數傳遞函數,請不要使用function(){}

使用fat arrow notation,讓你一個詞彙this

login(): void { 
    this.flag = true; 
    this.loginService.login(this.user).then((response) => { 
     console.log(this.flag); 
    }); 
} 
+0

謝謝@CozyAzure。有用。不幸的是,由於我的帳戶信用不足,公衆資料不可見。謝謝你的幫助。 – Darpan

+0

@Darpan你可以將它標記爲答案,如果它有效。 – CozyAzure

相關問題