2017-05-28 106 views
0

我是Angular的新手我試圖獲取JSON數據但無法獲取控制檯消息=無法加載資源:服務器響應狀態爲404(未找到)使用Http的角度提取數據無法加載

data.service.ts代碼是

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class DataService { 
private _url: string = "apidata/mydata.json"; 
constructor(private _http : Http) {} 

getSideNavTitle(){ 
return this._http.get(this._url) 
.map((response:Response) => response.json()); 
} 

testMethod() { 
return 'test page or file from the serices file'; 
} 

} 

service.test.component.ts

import { Component, OnInit } from '@angular/core'; 
import { DataService } from '../data.service'; 


const HEROES = [ 
{id: 1, name:'AAAAA'}, 
{id: 2, name:'BBBBB'}, 
]; 

@Component({ 
    selector: 'app-service-test', 
    templateUrl: './service-test.component.html', 
    styleUrls: ['./service-test.component.css'] 
}) 
export class ServiceTestComponent implements OnInit { 
setTitle = []; 
heroes = HEROES; 
titlepg:string; 

constructor(private _exampleService: DataService) { } 

ngOnInit() { 
this.titlepg = this._exampleService.testMethod(); 

this._exampleService.getSideNavTitle() 
.subscribe(resDataService => this.setTitle = resDataService); 

} 
} 

服務test.component.html

<div class="container"> 
<h1>{{ titlepg }}</h1> 
<div class="row"> 
<div class="col-md-3 topic-pad"> 
    <div class="list-group cour-nav-list"> 
    <a href="" class="list-group-item active"> First Title </a> 
    <a *ngFor="let titleKo of setTitle" href="" class="list-group-item list- 
    group-item-action">{{ titleKo.title}}</a> 
    </div> 
</div> 
</div> 
</div> 

和mydata.json是

[ 
{"id": 1, "title":"TitlePart-1"}, 
{"id": 2, "title":"TitlePart-2"}, 
{"id": 3, "title":"TitlePart-3"}, 
{"id": 4, "title":"TitlePart-4"}, 
{"id": 5, "title":"TitlePart-5"}, 
{"id": 6, "title":"TitlePart-6"}, 
{"id": 7, "title":"TitlePart-7"} 
] 
+0

如果你想加載json你需要使用服務器。 – hurricane

+0

@hurricane不能從文件中獲取數據嗎?如果沒有,那麼是否有免費的服務器可用,以便我可以嘗試? – Asumoon

+0

是的,您可以使用「npm install http-server」和「http-server」或創建簡單的nodejs服務器。 – hurricane

回答

0

如果你沒有服務器則向我們推薦的內存中的Web API。

製作如下修改代碼

在你app.ts

import { InMemoryDataService } from './in-memory-data.service'; 

@NgModule({ 
    imports: [ 
    InMemoryWebApiModule.forRoot(InMemoryDataService), 
    ] 

}) 

創造新的服務 -

import { InMemoryDbService } from 'angular-in-memory-web-api'; 
export class InMemoryDataService implements InMemoryDbService { 
    createDb() { 
    let yourvar = [ 
     {"id": 1, "title":"TitlePart-1"}, 
     {"id": 2, "title":"TitlePart-2"}, 
     {"id": 3, "title":"TitlePart-3"}, 
     {"id": 4, "title":"TitlePart-4"}, 
     {"id": 5, "title":"TitlePart-5"}, 
     {"id": 6, "title":"TitlePart-6"}, 
     {"id": 7, "title":"TitlePart-7"} 
    ]; 
    return {titles}; 
    } 
} 

在你data.service.ts使用URL

private myurl = 'api/yourvar'; 
+0

雅我從這裏得到了更多的信息https://angular.io/docs/ts/latest/tutorial/toh-pt6.html – Asumoon