2016-12-17 152 views
-2

角CLI的項目,在根文件夾我有一個文件lessons.ts(存儲數據)和app文件夾,我有教訓。 service.ts(檢索數據),代碼看起來像這樣:角2:http.get不明白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) 

有沒有人遇到過這種錯誤? 任何想法,將不勝感激!

+2

是什麼'/ lessons'? – micronyks

+0

'./lessons'是要提交lessons.ts的網址。我放在根文件夾 – Albert

+0

爲什麼你使用HTTP訪問它,如果它在你自己的應用程序的其他地方?我建議你閱讀例如https://angular.io/docs/ts/latest/tutorial/toh-pt4.html瞭解服務應該如何工作。實際上有一個使用TS文件中的靜態數據的例子。 – jonrsharpe

回答

0

簡單的答案是,

http.get('here make sure you have a valid url/path which points to 
      Webapi/Webservice/jsonfile etc..., which can actually return data').... 

在你的情況下,他們沒有,這就是爲什麼你得到一個錯誤。

2

你有一堆問題。首先,如果它可以工作,(它不會如何),你的路徑在http調用中是錯誤的,因爲你說lesson.ts在根文件夾中。

而且如上所述,爲什麼http如果你有靜態數據?這可能是一個解決方案...

不知道你的課實際上看起來的樣子......這可能是它:

export class Lesson { 
    id: number; 
    name: string; 
} 

那麼你lessons.ts文件看起來是這樣的...把它放在應用程序文件夾中。

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

或'返回Observable.of(LESSONS)',並相應更新組件,以保持一致的界面,如果長期目標是將其切換爲實際的API。 – jonrsharpe

+0

非常好的一點! – Alex