我正在尝试从面向问题的课程列表中动态导航到课程,因为未定义数据请帮我解决问题。
问题:名称未定义。
services :
import { Injectable } from '@angular/core';
import { Http, Response, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import{ICourses} from '../model/courses.model';
@Injectable()
export class CoursesService {
private coursesUrl = 'http://localhost:8000/courses';
constructor(private http: Http) {
}
getallCourses(){
return this.http.get(this.coursesUrl)
.map((res : Response) => res.json())
}
getCourseDetail(name: string) : Promise<ICourses> {
const url = `${this.coursesUrl}/${name}`;
console.log(url);
return this.http.get(url)
.toPromise()
.then(response => response.json().data as ICourses)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
component :
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, ParamMap} from '@angular/router';
import 'rxjs/add/operator/switchMap';
import {CoursesService} from '../../services/courses.service';
import{ ICourses } from '../../model/courses.model';
@Component({
selector: 'app-course-detail',
templateUrl: './course-detail.component.html',
styleUrls: ['./course-detail.component.css']
})
export class CourseDetailComponent implements OnInit {
icourses : ICourses;
constructor(
private coursesService: CoursesService,
private route: ActivatedRoute
) {}
ngOnInit() : void {
this.route.paramMap.switchMap((params: ParamMap) =>
this.coursesService.getCourseDetail(params.get('name')))
.subscribe(icoursesData => this.icourses = icoursesData )
}
}
HTML :
{{icoursesData.name}}