observer隐式有任何类型错误

时间:2017-02-14 04:52:08

标签: angular typescript rxjs

我想跟随 File Upload using (AngularJS 2) and ASP.net MVC Web API

来自upload.service.ts(注意://错误在错误行旁边添加)

 import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class UploadService {
    progress$: any;
    progress: any;
    progressObserver: any;
    constructor() {
        this.progress$ = Observable.create(observer//error => {
            this.progressObserver = observer
        }).share();
    }

    private makeFileRequest(url: string, params: string[], files: File[]): Observable/error {
        return Observable.create(observer//error => {
            let formData: FormData = new FormData(),
                xhr: XMLHttpRequest = new XMLHttpRequest();

            for (let i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    } else {
                        observer.error(xhr.response);
                    }
                }
            };

            xhr.upload.onprogress = (event) => {
                this.progress = Math.round(event.loaded / event.total * 100);

                this.progressObserver.next(this.progress);
            };

            xhr.open('POST', url, true);
            xhr.send(formData);
        });
    }
}

并收到错误:

  

错误TS7006参数'observer'隐式具有'any'类型

我尝试使用

(observer:Observable <any>) => 

的实例
(observer => 

并得到了这些错误

TS2339  Property 'next' does not exist on type 'Observable<any>'
TS2339  Property 'error' does not exist on type 'Observable<any>'
TS2339  Property 'complete' does not exist on type 'Observable<any>'
TS7006  Parameter 'observer' implicitly has an 'any' type

2 个答案:

答案 0 :(得分:3)

你的Observer需要一个类型参数,因为它的类型变量为T,而且它不是Observable<T>类型,而是Observer<T>类型

由于您使用next类型的参数调用number,因此它应为Observer<number>

import { Observer } from 'rxjs/Observer';

this.progress$ = Observable.create((observer: Observer<number>) => {
   // ...
})

makeFileRequest内的第二个Observable类型为string,因此需要Observer<string>才能正确编译。

答案 1 :(得分:2)

你得到“参数'观察者'隐含地有'任何'类型'错误,因为你没有明确地给你的observer变量一个类型并且你的TypeScript编译器已配置不允许这样做。

您可以做的第一件事是显式observer类型:

Observable.create((observer: any) => {
  // ....
})

请注意,类型仍然是any,但现在它是显式的,而不是隐式的。这应该纠正错误。

但是为observer提供真实类型更为准确,即Observer

import { Observer } from 'rxjs/Observer';

Observable.create((observer: Observer) => {
  // ....
})