I try to post datas by using templateDrivenForm directly and get datas from fireBase but show the following type error.
My part of codes
//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)
})
}
My error is
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});
the solution
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
The Firebase nested object can be converted to this data type in the map function:
responseData:{[key:string]:any}
private fetchPosts() {
this.http
.get('https://ng-complete-guide-b3d7f-default-
rtdb.firebaseio.com/posts.json')
.pipe(map(
(responseData:{[key:string]:any}) => {
const dataArray = [];
for (const key in responseData) {
if(responseData.hasOwnProperty(key)){
dataArray.push({ ...responseData[key], id:key})
}
}
return dataArray;
}))
.subscribe(posts => {
console.log(posts);
});
}
I agree that we should avoid using 'any' as much as possible. If you find a more accurate type compilable with the latest Angular version, please share it!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.