簡體   English   中英

錯誤 TS2339:“訂閱”類型上不存在屬性“訂閱”

[英]error TS2339: Property 'subscribe' does not exist on type 'Subscription

我在 Angular 8 中工作時遇到了一個問題。

service.ts 文件

 public getTopicsByContainerId(containerId) {
        var result;
        if (this.envUrl.accessMock == true) {
            result = topicsData;
            return of(result.filter(items => items.attributes.ContainerOid == containerId));
        }
        else {
            var url = this.getTopicsByContainerIdEndPoint.replace("{id}", containerId);
            return this.repository.getData(url).subscribe();
        }

    }

component.ts 文件

var output = this.homeService.getTopicsByContainerId(container_Oid).subscribe(res => {
   this.currentContainerTopics = res[0];
   });

現在的問題是我在從組件文件調用 Web 服務時遇到以下錯誤。

ERROR in src/app/home/home.component.ts(98,72): error TS2339: Property 'subscribe' does not exist on type 'Subscription | Observable<any>'.
  Property 'subscribe' does not exist on type 'Subscription'.

誰能告訴我我在哪里做錯了?

刪除.subscribe()

public getTopicsByContainerId(containerId) {
        var result;
        if (this.envUrl.accessMock == true) {
            result = topicsData;
            return of(result.filter(items => items.attributes.ContainerOid == containerId));
        }
        else {
            var url = this.getTopicsByContainerIdEndPoint.replace("{id}", containerId);
            // return this.repository.getData(url).subscribe();   // remove this line
            return this.repository.getData(url);   // this method should return Observable response
        }

    }

您需要將返回類型Observable<YourType>添加到您的方法getTopicsByContainerId()並刪除方法getTopicsByContainerId()內的subscribe方法:

public getTopicsByContainerId(containerId) : Observable<YourType> {
    var result;
    if (this.envUrl.accessMock == true) {
        result = topicsData;
        return of(result.filter(items => items.attributes.ContainerOid == containerId));
    }
    else {
        var url = this.getTopicsByContainerIdEndPoint.replace("{id}", containerId);
        return this.repository.getData(url);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM