【问题标题】:Angular/TypeScript - map received API-data from multiple tablesAngular/TypeScript - 映射从多个表接收到的 API 数据
【发布时间】:2021-11-30 00:13:28
【问题描述】:

我创建了我的后端,并且 api 控制器工作正常。 在前端,我已经为我的应用程序创建了模型:

book.model.ts

export class Book {
id : number;
autor: string;
title: string;
returnDate: Date;
numberOfExtensions: number;
cardId:number;
card?: Card;
status?:string;
}

card.model.ts

export class Card {
id : number;
validityDate: Date;
locked: boolean;
userId: number;
user?: User;}

和 user.model.ts

export class User {
id : number;
firstName: string;
lastName: string;
balance: number;}

在前端服务中,我通过以下方式从 api 获取数据:

export class DataService {
constructor(private http: HttpClient) { }

  readonly baseURL = "https://localhost:44302/api";
  books: Book[];
  users: User[];
  cards: Card[];
  postId: number;

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  async getBooks() {
    await this.http.get(this.baseURL + '/books')
      .toPromise()
      .then(result => this.books = result as Book[]);
  }
  async getCards() {
    await this.http.get(this.baseURL + '/cards')
      .toPromise()
      .then(result => this.cards = result as Card[]);
  }
  async getUsers() {
    await this.http.get(this.baseURL + '/users')
     .toPromise()
      .then(result => this.users = result as User[]);
  }
  async getData() {
    await this.getBooks();
    await this.getCards();
    await this.getUsers();
  }

最好先接收所有 SQL 数据吗?

下一步是映射。 例如每本书,我想用合适的ID(伪代码)保存卡片:

book.card = card where book.cardId === card.id

对于每张卡,我都想要卡的所有者-用户:

card.user = user where card.userId === user.id

如果有任何帮助,我将不胜感激! 非常感谢

【问题讨论】:

    标签: angular typescript api asp.net-core get


    【解决方案1】:

    一种可能的解决方案是使用forkJoin。这将在所有可观察对象完成时触发。在所有下载完成后,您可以操作您的数据。

    export class DataService {
    constructor(private http: HttpClient) { }
    
      readonly baseURL = "https://localhost:44302/api";
      books: Book[];
      users: User[];
      cards: Card[];
      postId: number;
    
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }
    
      getBooks() {
        return this.http.get(this.baseURL + '/books');
      }
      getCards() {
        return this.http.get(this.baseURL + '/cards');
      }
      getUsers() {
        return this.http.get(this.baseURL + '/users');
      }
      getData() {
        const observableList: Observable<any>[] = [];
        
        observableList.push(getBooks());
        observableList.push(getUsers());
        observableList.push(getCards());
        
        forkJoin(observableList).subscribe(resultList => {
          this.books = resultList[0] as Book[];
          this.users = resultList[1] as User[];
          this.cards = resultList[2] as Card[];
          
          // Do "book.card = card where book.cardId === card.id"
          const cardMap: Map<number, Card> = new Map();
          for (const card of this.cards) {
            cardMap.set(card.id, card);
          }
          for (const book of this books) {
            const card = cardMap.get(book.cardId);
            book.card = card;
          }
          
          // Do "card.user = user where card.userId === user.id"
          const userMap: Map<number, User> = new Map();
          for (const user of this.users) {
            userMap.set(user.id, user);
          }
          for (const card of this.cards) {
            const user = userMap.get(card.userId);
            card.user = user;
          }
        });
      }
    

    【讨论】:

    • 嘿,谢谢你的回答,太棒了!你将如何应用你用灰色写的这个条件映射?非常感谢!
    • 我的方法是这样的:this.books.forEach(b => { b.card = this.cards.filter(c => c.id === b.cardId)[0 ]; } 那是正确的方法吗?
    • 一个有效的方法是使用Map。您的方法需要 O(n^2)。通过使用Map,它将是 O(n)。我已经更新了我的答案。
    • 还有一个问题,如果我在我的组件中调用上述内容,例如“this.dataService.getData();”然后我尝试在我的组件中使用或显示数据我创建了一个本地数组并说:books: Book[];书籍 = this.dataService.books;但它一直告诉我数据未定义,即使数据是在网络选项卡中收到的
    • 在组件中我不再使用我的数组,而是使用我的地图对吗?
    猜你喜欢
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2018-11-02
    • 2021-12-04
    • 2022-08-20
    • 2017-05-02
    相关资源
    最近更新 更多