Summary
Questions
Service
import { IProjects } from './projects.interface'; @Injectable() export class ProjectsService { private _projectURL = '/dist/projects-list.json'; constructor(private _http: Http) { } getProjects(): Observable<IProjects[]> { return this._http.get(this._projectURL) .map((response: Response) => <IProjects[]> response.json()) .do(data => console.log('All: ' + JSON.stringify(data))) .catch(this.handleError); } getProject(id: number): Observable<IProjects> { return this.getProjects() .map((projects: IProjects[]) => projects.find(p => p.projectId === id)); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }
List Component that displays the list of projects
export class ProjectsListComponent implements OnInit { pageTitle = "Project List"; errorMessage: string; projects: IProjects[]; constructor(private _projectsService: ProjectsService) { } ngOnInit(): void { this._projectsService.getProjects() .subscribe(projects => this.projects = projects, error => this.errorMessage = <any>error); } onRatingClicked(message: string): void { this.pageTitle = 'Project List: ' + message; } }
Any help would be greatly appreciated :)
you need add your mock json file in the assets
folder in your angular project.
and you can access like this
getProjects(): Observable<IProjects[]> {
return this._http.get("assets/projects-list.json")
.map((response: Response) => <IProjects[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
Note:- you need add static file like image or config file in the assets folder. angular can only access assets folder.
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.