繁体   English   中英

类型 {} 上不存在属性“订阅”

[英]Property 'subscribe' does not exist on type {}

服务.ts

   import { Injectable } from '@angular/core';

    const RELEASES = [
{
  id: 1,
  title: "Release 1",
  titleUrl: "release-1",
  year: "2016"
},
{
  id: 2,
  title: "Release 2",
  titleUrl: "release-2",
  year: "2016"
},
{
  id: 3,
  title: "Release 3",
  titleUrl: "release-3",
  year: "2017"
}

]

   @Injectable()
   export class ReleaseService {
     visibleReleases =[];

     getReleases(){
       return this.visibleReleases = RELEASES.slice(0);
     }

     getRelease(id:number){
       return RELEASES.slice(0).find(release => release.id === id)
     }

   }

组件.ts

   import { Component, OnInit, OnDestroy } from '@angular/core';
   import { ReleaseService } from '../service/release.service';
   import { ActivatedRoute, Params } from '@angular/router';
   import { IRelease } from '../releases/release';

   @Component({
     selector: 'app-details',
     templateUrl: './details.component.html',
     styleUrls: ['./details.component.css']
   })
   export class DetailsComponent implements OnInit {
     private sub: any;
     private release: string[];

     constructor(
       private _releaseService: ReleaseService,
       private route: ActivatedRoute
     ) { }

     ngOnInit() {
       this.sub = this.route.params.subscribe(params => {
           let id = params['id'];
           this._releaseService.getRelease(id).subscribe(release => this.release = release);
       });    
     }

     ngOnDestroy() {
       this.sub.unsubscribe();
     }

   }

释放接口

   export class IRelease {
       id: number;
       title: string;
       titleUrl: string;
       year: string;
   }

我正在尝试在我的 Angular4 应用程序中创建一个“详细信息页面”。 我想要的是通过以下代码返回所选项目:

ngOnInit() {
       this.sub = this.route.params.subscribe(params => {
           let id = params['id'];
           this._releaseService.getRelease(id).subscribe(release => this.release = release);
       });    
     }

并且有一个错误:属性 'subscribe' 不存在于类型 '{ id: number; 标题:字符串; titleUrl:字符串; 年份:字符串; }'。

我做错了什么?

您的ReleaseService#getRelease()方法返回普通对象,您不需要订阅它。 订阅仅适用于可观察对象(更多关于它们的信息,例如此处)。

你可以简单地做:

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
        let id = params['id'];
        this.release = this._releaseService.getRelease(id);
    });    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM