我是Angular和TypeScript的新手:)我有一个让我头疼的问题......
我有以下组件:
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {
analysisType: string = "Posts";
limit: number = initLimitValue;
posts$!: Observable<Post[]>;
constructor(public dataCollectorService: DataCollectorService) { }
ngOnInit(): void {
this.posts$ = this.dataCollectorService.squeezePosts(this.analysisType, this.limit).pipe(debounceTime(400), distinctUntilChanged());
}
}
这是模板:
<div class="posts-div">
<div *ngFor="let post of posts$ | async | keyvalue">
{{ post.value.title }}
</div>
</div>
此组件正在使用以下服务:
@Injectable({
providedIn: 'root'
})
export class DataCollectorService {
private url = 'http://localhost:8080/mydata/';
constructor(private http: HttpClient) {
}
squeezePosts(analysisType: string, limit: number): Observable<Post[]>{
return this.http.get<Post[]>(`${this.url}${analysisType}/"none"/none"/${limit}`)
.pipe(
catchError(this.handleError<Post[]>('squeezePosts', undefined))
);
}
private handleError<T>(operation='operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
console.log(operation + ' failled: ' + error.message);
return of(result as T);
}
}
}
这是我从本地主机服务器得到的响应:
{
"0": {
"title": "0 - My title test",
"selftext": "0 - My selftext test, My selftext test. My selftext test ..."
},
"1": {
"title": "1 - My title test",
"selftext": "1 - My selftext test, My selftext test. My selftext test ..."
}
}
这是我的Post
接口:
export interface Post {
title: string,
selftext: string
}
最后,这是我无法摆脱的错误:
属性“title”在类型“number”上不存在|岗位|(()=> string)|(()=> string)|(()=>发布|undefined)|((...items:Post[])=> number)|{(...items:ConcatArray[]):Post[];(...items:(员额|String <...>[]):String [];}|还有25个|((searchElement:Post,fromIndex?:数量|undefined)=> boolean)'。
属性“title”在类型“number”上不存在。
你能帮我解决这个错误吗?
1条答案
按热度按时间qhhrdooz1#
根据你的回答,它不是Post(
Post[]
)的数组。但它是key-value pair/dictionary的集合,key为
string
type,value为Post
type。方案一:
Map<string, Post>
使用
Observable<Map<string, Post>>
类型声明posts$
。data-collector.service.ts
posts.component.ts
Sample Solution 1 on StackBlitz
方案二:
KeyValuePair<Post>
KeyValuePair
。Observable<KeyValuePair<Post>>
类型声明posts$
。key-value-pair.ts
data-collector.service.ts
posts.component.ts
Sample Solution 2 on StackBlitz