Angular 12 如何 return 一个 http 获取请求对象数组并使用 map() 分配给其他不同类型的数组

Angular 12 how to return an http get request array of objects and assign to other array of different type using map()

嘿,我正在尝试按照此示例实施 bootstrap5 下拉菜单:Creating Multi-Select Dropdown with Angular and Bootstrap 5 在那个例子中,为了获取数据,他使用 app.service 和 returns 一个对象数组:

getFoods(): Food[] {
        return [
            {
                id: 1,
                name: 'Grapes'
            },
            {
                id: 2,
                name: 'Melon'
            },
...

然后在他的 ngOnInit() 中调用 getFoods() 方法并使用 .map() 运算符,因为他必须分配值,因为项目模型有两个值:

ngOnInit(): void {
        this.items = this.appService.getFoods().map(fruit => ({
            id: fruit.id,
            name: fruit.name
        } as Item));
    }

所以我正在尝试做帽子,但是使用 HTTP GET 请求从 API 端点获取数据。 但是我不知道如何使用 .map() 运算符来获取 http get 请求:

this.subscription = this.contactSearchService.currentCodes.pipe(
            map(
                code => (
                    {
                        id: code.code,
                        name: code.code
                    }
                )
            )).subscribe(Response => {
                this.items = Response
            })

它给我这些错误:

Property 'code' does not exist on type 'ResponsibilityCode[]'.
Type '{ id: any; name: any; }' is missing the following properties from type 'Item[]': length, pop, push, concat, and 26 more.

我的http get请求函数:

private _reponsibilityCodeSource = new BehaviorSubject<ResponsibilityCode[]>([]);
currentCodes = this._reponsibilityCodeSource.asObservable();

getCodes(): void {
    this.http.get<ResponsibilityCode[]>('https://localhost:44316/api/SITEContacts/ResponsibilityCode').subscribe(Response => {
        this._reponsibilityCodeSource.next(Response);
      });
  }

I get the data as `JSON` btw.

rxjs pipe(map(.... code...)) 不同于 array.map - pipe(map()) 不对数组的每一项进行操作

所以你得到的错误是因为你正在为单个项目换出 ResponsibilityCode 数组(代码中的code 是所有责任代码)

尝试

this.subscription = this.contactSearchService.currentCodes.subscribe(Response => {
                this.items = Response.map(
                code => (
                    {
                        id: code.code,
                        name: code.code
                    }
                )
            )
})

您的 HTTP 获取 returns 一个 ResponsibilityCode 数组的 Observable,因此要实现这一点,您必须 map (Array.prototype.map) the items of the array within the RxJS's map 运算符,如下所示:

this.subscription = this.contactSearchService.currentCodes
  .pipe(
    map((res: ResponsibilityCode[]) =>
      res.map((item) => ({
        id: item.id,
        name: item.name,
      }))
    )
  )
  .subscribe((res) => {
    this.items = res;
  });