我是Angular的新手我正在尝试获取json数据但无法获取控制台消息=无法加载资源:服务器响应状态为404(未找到)
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 :(得分: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中使用网址
private myurl = 'api/yourvar';