我对PrimeNG进行了培训,并创建了一项服务来从json文件中获取数据。 https://www.primefaces.org/primeng/#/treetable
但是无法获取json数据。
使用:
从组件调用该方法ngOnInit() {
this.nodeService.getFileSystem().then(files => this.files = files);
}
我正在服务中使用此方法:
private filesystemUrl = 'http://localhost:4200/assets/data/filesystem.json';
constructor(private http: HttpClient) { }
getFileSystem() {
return this.http.get(this.filesystemUrl)
.toPromise()
.then(res => <TreeNode[]> res);
}
控制台显示:
ERROR错误:未捕获(按承诺):对象: {“ body”:{“ error”:“集合“数据”不正确 found“},” url“:” http://localhost:4200/assets/data/filesystem.json“,” headers“:{” normalizedNames“:{},” lazyUpdate“:null},” status“:404,” statusText“:” Not 找到”} 在resolvePromise(zone.js:814) 在resolvePromise(zone.js:771) 在zone.js:873 在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask (zone.js:421) 在Object.onInvokeTask(core.js:3811) 在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask (zone.js:420) 在Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask(zone.js:188) 在rainMicroTaskQueue(zone.js:595) 在push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask(zone.js:500) 在ZoneTask.invoke(zone.js:485)
如果我在控制台消息上单击“ URL”:“ http://localhost:4200/assets/data/filesystem.json”,则可以访问json文件,因此应该是另一个问题。 该文件位于“ assets / data / filesystem.json”中,我修改了angular.json:
"assets": [
"src/favicon.ico",
"src/assets",
"src/assets/data"
]
主要奇怪的是,在浏览器的“网络”选项卡中,我没有看到尝试访问此json文件的任何get调用:
localhost 304 document vendor.js:100488 210 B 304 ms
runtime.js 304 script (index) 211 B 4 ms
polyfills.js 304 script (index) 212 B 6 ms
styles.js 304 script (index) 212 B 7 ms
vendor.js 304 script (index) 213 B 17 ms
main.js 304 script (index) 212 B 17 ms
info?t=1539698839604 200 xhr zone.js:2969 367 B 2 ms
websocket 101 websocket sockjs.js:1683 0 B Pending
我尝试了其他方法来编写我的方法,例如在我的IDE中看起来不错的方法:
getFileSystem() {
return this.http.get(this.filesystemUrl)
.pipe(map((response: Response) => {
console.log(response.json());
return response.json();
}))
.subscribe();
}
但是,在调用服务的组件方法中,我没有找到更改“ then()”的方法,因为:[ts]属性'then'在'Subscription'类型上不存在。
我也尝试过这样的服务方法,因为在服务或组件中IDE中没有显示错误,没关系:
getFileSystem() {
return this.http.get<TreeNode[]>(this.filesystemUrl);
}
但是在控制台中出现:
错误{body:{…},网址: “ http://localhost:4200/assets/data/filesystem.json”,标题: HttpHeaders,状态:404,statusText:“未找到”}正文:{错误: “未找到集合'数据'”}标头:HttpHeaders {normalizedNames: Map(0),lazyUpdate:空,lazyInit:ƒ}状态:404 statusText:“否 找到的” URL:“ http://localhost:4200/assets/data/filesystem.json” 原始:对象
是否有人可以提供帮助?非常感谢!
答案 0 :(得分:0)
像这样创建服务:
private filesystemUrl = 'http://localhost:4200/assets/data/filesystem.json';
constructor(private http: HttpClient) { }
getFileSystem(): Observable<TreeNode[]> {
return this.http.get<TreeNode[]>(this.filesystemUrl);
}
您要返回一个Observable,必须在组件中订阅它:
private treeNode: TreeNode[];
ngOnInit() {
this.nodeService.getFileSystem().subscribe(data => {
this.treeNode=data;
console.log(data);
});
}