首页 文章

属性'subscribe'在类型{}上不存在

提问于
浏览
-3

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 interface

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

我做错了什么?

1 回答

  • 1

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

    你可以简单地做:

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

相关问题