【发布时间】:2021-11-26 13:59:08
【问题描述】:
我正在尝试创建一个从包含帖子数组的 json 文件中获取帖子的服务。
我已经有一个使用 HttpClient 返回 json 文件内容的服务。
目标是显示完整的帖子内容。
获取 json 文件的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetJsonFileService {
constructor(private http: HttpClient) {}
getJsonFile(jsonFile: string /* the file path is set by components */){
return this.http.get(jsonFile,{observe: 'body', responseType: 'json'});
}
}
通过 id 获取帖子的服务:
import { Injectable } from '@angular/core';
import { GetJsonFileService } from './get-json-file.service';
@Injectable({
providedIn: 'root'
})
export class GetPostService {
constructor(private getJsonFileservice: GetJsonFileService) {}
getPost(id: number) :object{
var post!: object;
this.getJsonFileservice.getJsonFile('assets/posts.json').subscribe((data :any)=>{
post = data["posts"][id];
});
return post;
}
}
显示帖子的组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GetPostService } from '../services/get-post.service';
@Component({
selector: 'app-post-view',
templateUrl: './post-view.component.html',
styleUrls: ['./post-view.component.scss']
})
export class PostViewComponent implements OnInit {
_post!: object;
id!: number;
constructor(private route: ActivatedRoute, private getPost: GetPostService){}
ngOnInit(){
var id!: number;
this.route.params.subscribe(params=>{
id = params.id;
});
this._post = this.getPost.getPost(id);
}
}
当我尝试在组件模板中显示以下内容时:
{{_post.title}}
我收到此错误:
Errors while compiling. Reload prevented.
在 vscode 中打字稿告诉我:
Property 'title' does not exist on type 'object'
我尝试了@msanford 的解决方案。
在后视图中还有一件事要改变,但我真的不知道该怎么做:
posts["posts"][id]
打字稿给我一个错误:
Element implicitly has an 'any' type because expression of type '"posts"' can't be used to index type 'Object'.
Property 'posts' does not exist on type 'Object'
有什么想法吗?
【问题讨论】:
-
posts["posts"][id]给你一个访问器错误:数据结构实际上是什么样的,你能分享一下吗?我只是从您的问题中重复了data["posts"][id];。 -
(请注意,还有其他几项需要更改。)
-
@msanford ,是的,我通过检查 observable link 的文档发现了几个问题,看来我必须改变很多事情。但你的回答帮助我理解了可观察的东西。谢谢
标签: angular typescript observable