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

时间:2017-10-22 09:00:29

标签: javascript angular rxjs observable subscribe

Service.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)
     }

   }

Component.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();
     }

   }

IRelease界面

   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:string;年:字符串; }”。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

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

您可以这样做:

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