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;
}
I'm trying to create a "Detail page" in my Angular4 app. What I want is to return a chosen item by the code below:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this._releaseService.getRelease(id).subscribe(release => this.release = release);
});
}
And there's an error: Property 'subscribe' does not exist on type '{ id: number; title: string; titleUrl: string; year: string; }'.
What have I done wrong?
Your ReleaseService#getRelease()
method returns plain object, you do not need to subscribe to it. Subscribe is only for observables (more about them eg here ).
You can simply do:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this.release = this._releaseService.getRelease(id);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.