我正在使用TypeScript和Angular JS編寫將處理POST和GET請求到服務器的通用服務。從常用服務調用函數時,TypeScript服務未定義
這就是服務的樣子:
module TBApp {
export class apiService {
static $inject = ['$http', 'notificationService'];
constructor(private $http, private notificationService: notificationService) {
}
get(url, config, success, failure) {
return this.$http.get(url, config)
.then(result => { this.handleResponse(result, success); }, result => { this.handleError(result, failure) });
}
post(url, data, success, failure) {
return this.$http.post(url, data)
.then(result => { this.handleResponse(result, success); }, result => { this.handleError(result, failure) });
}
handleResponse(result, success) {
this.notificationService.displaySuccess(result.data.message);
success(result);
}
handleError(result, failure) {
if (result.status === '401') {
this.notificationService.displayError('Authentication required.');
//TODO: redirect to login page
}
else if (failure !== null) {
failure(result);
}
}
}
}
所以在控制器下面所示我想打電話給loginCompleted
上登錄成功。
module TBApp {
export class loginController extends MyApp.BaseController {
membershipService: membershipService;
apiService: apiService;
static $inject = ['$scope', 'membershipService', 'apiService', '$location'];
constructor($scope, membershipService: membershipService, apiService: apiService, private $location) {
super($scope);
this.scope.user = new User(null, null);
this.membershipService = membershipService;
this.apiService = apiService;
}
login() {
// HERE: this.membershipService Is NOT NULL OR UNDEFINED
console.log(this.membershipService);
this.apiService.post('/api/account/authenticate', this.scope.user, this.loginCompleted, this.loginFailed);
}
loginCompleted(response) {
//This method will save the logged in user to cookies
//HERE : this.membershipService Is UNDEFINED
this.membershipService.saveCredentials(this.scope.user);
// redirect to home page
this.$location.path('/');
}
loginFailed(response) {
alert('login failed');
console.log(response);
}
}
}
函數被調用一切工作除了this.membershipService
是loginCompleted()
函數內部不確定的。
我覺得這是因爲loginCompleted()
函數是從apiService
裏面調用的,我該如何解決呢?我究竟做錯了什麼?
使用綁定上下文是否存在任何性能問題? –
@DawoodAwan,沒有任何性能問題,但是當您使用TypeScript時,不建議使用綁定。這裏是[文章](https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html)。 – Mikki
那麼如何實現上述邏輯而不使用綁定 –