Java TS7053:元素隐式具有';任何';类型,因为表达式的类型为';字符串';can';t用于索引类型';对象';
我试图通过直接使用templateDrivenForm发布数据,并从fireBase获取数据,但显示以下类型错误 我的代码部分Java TS7053:元素隐式具有';任何';类型,因为表达式的类型为';字符串';can';t用于索引类型';对象';,java,html,css,angular,typescript,Java,Html,Css,Angular,Typescript,我试图通过直接使用templateDrivenForm发布数据,并从fireBase获取数据,但显示以下类型错误 我的代码部分 //directly posts datas using submitButton from templateDrivenForm onCreatePosts(postDatas:{title:string, content:string}){ this.http.post('https://ng-complete-guide-b3d7f-default-rtdb.f
//directly posts datas using submitButton from templateDrivenForm
onCreatePosts(postDatas:{title:string, content:string}){
this.http.post('https://ng-complete-guide-b3d7f-default-rtdb.firebaseio.com/posts.json',
postDatas)
.subscribe(
responseData => {
console.log(responseData);
});
}
//get datas from database
private fetchPost(){
return this.http.get('https://ng-complete-guide-b3d7f-default-rtdb.firebaseio.com/posts.json')
.pipe(map(responseData => {
const dataArray = [];
for(let key in responseData){
if(responseData.hasOwnProperty(key)){
dataArray.push({...responseData[key], id:key});
}
}
return dataArray;
}))
.subscribe( responseData => {
console.log(responseData)
})
}
我的错误是
Error: src/app/app.component.ts:40:28 - error TS7053: Element implicitly has an 'any' type
because
expression of type 'string' can't be used to index type 'Object'.
No index signature with a parameter of type 'string' was found on type 'Object'.
40 dataArray.push({...responseData[key], id:key});
解决方案
private fetchPost(){
return this.http.get('https://ng-complete-guide-b3d7f-default-
rtdb.firebaseio.com/posts.json')
.pipe(map((responseData:{[data:number]:any}) => {
const dataArray = [];
for(let key in responseData){
if(responseData.hasOwnProperty(key)){
dataArray.push({...responseData[key], id:key});
}
}
return dataArray;
}))
.subscribe( responseData => {
console.log(responseData)
})
}
.pipe(map((responseData:{[data:number]:any}) //object type
我认为您的id是一个字符串,您应该尽量避免使用
any
。类型应该是{[key:string]:{content:string,title:string}
您可以在函数中合并posts对象(至少部分)并显示哪些字段?但是在您的位置上,我建议您使用一个特殊的库来处理firebase,而不是使用RESTAPI(与库相比,它非常有限)