내가 작업하고있는 프로젝트에서 나는 많은 의미를 가지지 않는 상황을 발견했다. 강력히 의심 스럽네요, 내가 TypeScript에서 일하고있는 동안, 내 특별한 문제는 javascript의 재미있는 뉘앙스 때문인 것으로 의심됩니다. 그러나 그것을 증명하거나 수정하는 방법을 모르겠습니다. 내가 일하고 있어요 응용 프로그램에 대한
배경
내가 일반적으로하는 것과 다른 유일한 점은 $http.get(...).then(...)
성공 콜백에 대해 TypeScript의 'lambda'구문을 사용하는 대신 클래스 함수를 사용하고 있기 때문입니다. A) 사용중인 코드가 실제로 오류 콜백을 사용하고, B) $http.get(...).then(success, error)
구문은 람다 구문으로 읽는 것이 지저분합니다.
그래서, 당신은이 서비스를 호출 할 때마다 $http
GET이 성공적으로 수행
namespace MyApp.Models {
export class WebApiResult<T> {
public data: T;
}
}
namespace MyApp.Services {
export class SomeService {
public status: SomeServiceStatus = new SomeServiceStatus();
public static $inject: string[] = ['$http'];
public constructor(
public $http: ng.IHttpService
) {
}
public doSomething(): ng.IPromise<SomeServiceStatus> {
this.$http.get('/api/some/SomeAction')
.then(this.onDoSomethingSuccess, this.describeError);
}
// This is the problem method. When this code runs,
// a type error is generated.
public onDoSomethingSuccess(result: Models.WebApiResult<SomeServiceStatus>): SomeServiceStatus | ng.IPromise<SomeServiceStatus> {
if(!result.data.isInSpecialState) {
return result.data;
}
// TypeError! Can't assign to undefined.
this.status = result.data;
return result.data;
}
public describeError(error: any) {
alert('oops');
}
}
export class SomeServiceStatus {
public isInSpecialState: boolean = false;
public someStatusMessage: string = '';
public someIdentifier: string = '';
}
angular
.module('app')
.service('someService', SomeService);
}
문제 :
// Not pretty, but sufficient.
this.$http.get(...).then(() => { ... });
// Ewwww...
this.$http.get(...)
.then(() => {
...
},() => {
...
});
// Much better!
this.$http.get(...)
.then(onFooSuccess, onError);
다음은 관련 서비스입니다. 그러나 성공한 콜백이 문제입니다. 즉, this.status = result.data
행에 도달하면 result.data
을 status
의 undefined
에 할당 할 수 없기 때문에 항상 예외가 발생합니다. 현재
, 내 이론은 this
실제로 오히려 어쩌면 클래스 메소드는 대리인으로 사용되는 다른 것을는 SomeService
를 참조하지만 않는다는 것입니다.
질문
이 이론은 몇 가지 질문을 유발합니다.
- 정확히
this
은 무엇입니까? Visual Studio 2015에서이 도움말 위로 마우스를 가져 가면 '도움이되는'텍스트 인this: this
이 표시됩니다. Microsoft에 감사드립니다. this
도이 작업을 수행해야합니까? 이 글은 TypeScript 버그인가요, 아니면 단지 생성 된 자바 스크립트로 저 자신을 발로 쏘는 것입니까?- 성공 및 오류 콜백을 모두 가지고있는 AngularJS 약속을 처리 할 때 권장되는 문체가 있습니까? 내가 코드를 작성하는 더 좋은 방법을 보지 못하거나 단순히 뭔가를 모르는 것일 수도 있습니다. 그것은 SO 질문을하는 것이 나에게 뭔가를 가르쳐 준 것은 처음이 아닐 것입니다.
당신이'this'와'typescript' /'javascript' 태그 다른 질문을보고 했습니까? –
질문을하기 전에 검색을했지만이 경우를 처리 한 내용을 찾지 못했습니다. 또한, 독자가 매우 빠른 독자가 아니라면, 내 질문을 읽었는지 확신 할 수 없습니다. –
문제가 무엇인지 알기 위해 전체 질문을 읽을 필요가 없습니다. 오히려 명백합니다. . ' 공공 해봐요() : –