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"}
]
如果你想加載json你需要使用服務器。 – hurricane
@hurricane不能從文件中獲取數據嗎?如果沒有,那麼是否有免費的服務器可用,以便我可以嘗試? – Asumoon
是的,您可以使用「npm install http-server」和「http-server」或創建簡單的nodejs服務器。 – hurricane