Angular Cli项目,在根文件夹我有一个文件 lessons.ts (用于存储数据)和 app文件夹,我有 lesson.service.ts (要检索数据),代码如下所示:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs';
//import Lesson
import { Lesson } from './lesson.class';
@Injectable()
export class LessonService {
lessons=[];
constructor(private http: Http) {
this.loadLessons();
}
loadLessons(){
this.http.get('./lessons')
.map(res=>res.json())
.subscribe(
lessons=>this.lessons =lessons,
err => console.log(err)
)
}
}
控制台抛出了一条错误消息:
zone.js:1382 GET http://localhost:4200/lessons 404 (Not Found)
要修复它,我修改了 lessons.service.ts
.....
this.http.get('./lessons.ts') ->I added '.ts' for lessons file
...
但浏览器不断抛出错误:
zone.js:1382 GET http://localhost:4200/lessons.ts 404 (Not Found)
有没有人遇到过这个bug? 任何想法都将不胜感激!
答案 0 :(得分:2)
你有很多问题。首先,如果它可以工作,(它不会如何),你的路径在http调用中是错误的,因为你说lesson.ts在根文件夹中。
如上所述,为什么http如果你有静态数据?这可能是一个解决方案......
不知道你的课程究竟是什么样的......这可能就是这样:
export class Lesson {
id: number;
name: string;
}
然后你的lessons.ts文件看起来像这样......把它放在app文件夹中。
import { Lesson } from './lesson.class';
export const LESSONS: Lesson[] =
{id: 1, name: 'lesson1'},
{id: 2, name: 'lesson2'}
];
lesson.service.ts:
import { Injectable } from '@angular/core';
//import Lesson
import { Lesson } from './lesson.class';
import { LESSONS } from './lessons';
@Injectable()
export class LessonService {
loadLessons(){
return LESSONS;
}
}
显示课程的组件:
import { Component, OnInit } from '@angular/core';
import { Lesson } from './lesson.class';
import { LessonService } from './lesson.service';
export class AppComponent implements OnInit {
constructor(private lessonService: LessonService) { }
lessons: Lesson[];
ngOnInit {
this.lessons = this.lessonService.loadLessons();
}
}
同样评论,请查看服务:Tour of heroes
答案 1 :(得分:0)
简单的答案是,
http.get('here make sure you have a valid url/path which points to
Webapi/Webservice/jsonfile etc..., which can actually return data')....
在你的情况下,它们都不是你收到错误的原因。