Angular-如何确保数据仅加载一次

时间:2019-05-15 10:59:53

标签: angular typescript

当页面被加载时,数据被正确地提取并显示,然后在离开页面时,数据被再次提取并加倍到当前数组中。如果我有物品:A,B,C,那么我将有A,B,CA,B,C

现在,我让组件放置一个简单的是否要检查是否需要再次获取数据的函数。但是,它似乎被绕过了。我看过this and this as well as this

//home.ts

export class Home implements OnInit, OnDestroy{
  conversations: Array<any>; 

async ngOnInit() {
  this._chatInit();
}

private async _chatInit() {
  this.dataService.loadConversations(); //getter for local storage

  const data = this.messageStorage.hasChats();

  if (data.length) {
    //there is data already loaded
    this.conversations = data;
  } else {
    //there is an empty array, subscribe to it.
    this.messageStorage
    .getChatList$()
    .subscribe(conversation => {
      console.log('Conversation', conversation)
      this.conversations = conversation;
    });
  }
}

//dataService
export class DataService {

  //the object where it is all stored
  private conversations: any = {
    peerToPeer: {},
    groups: {},
  };

  private listOfChats: Array<any> = new Array<any>();
  private bsListOfChats$: BehaviorSubject<any> = new BehaviorSubject<any>(this.listOfChats); 

  public loadConversations() {
    this.storage.get('conversations').then(chat=> {
      this.conversations = chat;
      this.formatChats(this.conversations);//converts the Object to an Array so *ngFor directive can be used
   });
  }

  public hasChats() {
    return this.listOfChats;
  }

  public getChatList$() {
    return this.bsListOfChats$;
  }

}

为澄清起见,我要执行的操作是一次加载n个聊天。当我离开页面并返回时,我希望加载相同的n,不多也不少。

感谢大家的帮助!

2 个答案:

答案 0 :(得分:1)

看看TransferState,它用于在服务器端(通用角度)和客户端之间传输数据,但是我认为只将其用于客户端是可以的

import {makeStateKey, TransferState} from '@angular/platform-browser';

export class DataService {

//the object where it is all stored
private conversations: any = {
    peerToPeer: {},
    groups: {},
};

constructor(
    private state: TransferState,
) {

}

private listOfChats: Array<any> = new Array<any>();
private bsListOfChats$: BehaviorSubject<any> = new BehaviorSubject<any>(this.listOfChats);

public loadConversations() {
    const stateKey = makeStateKey('conversations'); // 1 create stateKey
    const data = this.state.get(stateKey, null as any); // 2 get data from state
    if (data) { // 3 if data in state use it
        this.conversations = data;
    } else {
        this.storage.get('conversations').then(chat=> {
            this.conversations = chat;
            this.formatChats(this.conversations);//converts the Object to an Array so *ngFor directive can be used
            this.state.set(stateKey, {...this.conversations}); // 4 set data to storage
        });
    }
}

public hasChats() {
    return this.listOfChats;
}

public getChatList$() {
    return this.bsListOfChats$;
}

}

快速编辑代码,可以用更好的方式重写

答案 1 :(得分:0)

执行此操作:

@Component({
  //...
  changeDetection: ChangeDetectionStrategy.OnPush
})

签出:https://blog.angular-university.io/how-does-angular-2-change-detection-really-work/