typescript Angular:异步|keyvalue -->属性'X'在类型'X'上不存在

r9f1avp5  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(153)

我是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”上不存在。
你能帮我解决这个错误吗?

qhhrdooz

qhhrdooz1#

根据你的回答,它不是Post(Post[])的数组
但它是key-value pair/dictionary的集合,key为string typevalue为Post type

{
    "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 ..."
        }
}

方案一:Map<string, Post>

使用Observable<Map<string, Post>>类型声明posts$
data-collector.service.ts

squeezePosts(analysisType: string, limit: number): Observable<Map<string, Post>> {
    return this.http
       .get<Map<string, Post>>(`${this.url}${analysisType}/"none"/none"/${limit}`)
       .pipe(catchError(this.handleError<Map<string, Post>>('squeezePosts', undefined)));
}

posts.component.ts

posts$!: Observable<Map<string, Post>>;

Sample Solution 1 on StackBlitz

方案二:KeyValuePair<Post>

  • 使用泛型类型创建接口KeyValuePair
  • 使用Observable<KeyValuePair<Post>>类型声明posts$

key-value-pair.ts

export interface KeyValuePair<T> {
  [key: string]: T;
}

data-collector.service.ts

import { KeyValuePair } from '../models/key-value-pair';

squeezePosts(
    analysisType: string,
    limit: number
  ): Observable<KeyValuePair<Post>> {
     return this.http
       .get<KeyValuePair<Post>>(`${this.url}${analysisType}/"none"/none"/${limit}`)
       .pipe(catchError(this.handleError<KeyValuePair<Post>>('squeezePosts', undefined)));
}

posts.component.ts

import { KeyValuePair } from '../models/key-value-pair';

posts$!: Observable<KeyValuePair<Post>>;

Sample Solution 2 on StackBlitz

相关问题