如何在Typescript中实现$ http?

时间:2015-09-22 01:48:30

标签: angularjs typescript

我在Typescript中定义$ http调用时遇到问题。以前我像这样使用.success和.error:

this.$http({
            method: "GET",
            url: self.ac.dataServer + url
        })
            .success((data: any, status: number, headers: (headerName: string) => string, config: ng.IRequestConfig): void => {
                self.topics = angular.copy(data);
                self.topicsBase = angular.copy(data);
                this.$state.transitionTo('home.subjects.subject.admin.topics', {
                    subjectId: this.sus.subject.id
                });
            })
            .error((data, status, headers, config): void => {
                self.topics = null;
                self.topicsBase = null;
            })
            .finally((): void => {
            });

现在我改用了.then:

 this.$http({
            method: "GET",
            url: self.ac.dataServer + url
        })
            .then(
            (response): any => {
                self.topics = angular.copy(response.data);
                self.topicsBase = angular.copy(response.data);
                this.$state.transitionTo('home.subjects.subject.admin.topics', {
                    subjectId: this.sus.subject.id
                });},
            (response): any => {
                self.topics = null;
                self.topicsBase = null;
            }
            );

但这给了我以下错误:

  

严重级代码说明项目文件行   错误TS2322类型' {}'不能指定类型' ITopic []'。   物业长度'在' {}'中缺少。 admin C:\ H \ admin \ admin \ app \ services \ topicservice.ts 214   严重程度代码说明项目文件行错误TS2322类型' {}'是   不能分配给类型   ' ITopic []&#39 ;. admin C:\ H \ admin \ admin \ app \ services \ topicservice.ts 215

错误出现在我为self.topics和self.topicsBase指定angular.copy(数据)的行上

1 个答案:

答案 0 :(得分:2)

  

类型'(data: IHttpPromiseCallbackArg<{}>, status: any, headers: any, config: any) => any'的参数不能分配给'(response: IHttpPromiseCallbackArg<{}>) => any'类型的参数

您传递的参数比$http()返回的参数多。

修正:

$http({
    method: "GET",
    url: myURL
})
    .then((response): any => { },(): any => {});