ค้นหาเว็บไซต์

typescript - รวมหลายการเลือก store ของ ngrx เป็นการเรียกครั้งเดียวใน Angular 7


โดยพื้นฐานแล้วฉันต้องทำการเรียก 3 ครั้งไปยัง ngrx สโตร์ของฉัน

ดังนั้นสิ่งที่ฉันมีคือ

getUserInfo() {
    this._store.select('userInfo')
       .subscribe(result => this.userInfo = result);
}

getCats() {
    this._store.select('cats')
       .subscribe(result => this.cats = result);
}

getDogs() {
    this._store.select('dogs')
        .subscribe(result => this.dogs = result);
}

ตอนนี้ฉันกำลังพยายามย่อสิ่งนี้ให้อยู่ในวิธีการเดียว ดังนั้นฉันจึงลองแบบนี้

ฉันกำลังนำเข้า rxjs แบบนี้

import { combineLatest } from 'rxjs';
import { tap, filter } from 'rxjs/operators';

และนี่คือวิธีของฉัน

getStoreData() {
    combineLatest(
        this._store.select('userInfo'),
        this._store.select('cats'),
        this._store.select('dogs')
    ).pipe(tap(([userInfo, cats, dogs]) => console.log(userInfo, cats, dogs));
}

ฉันกำลังเรียกใช้เมธอดของฉันแบบนี้

ngOninit() {
   this.getStoreData()
}

ปัญหาของฉันคือวิธีนี้ถูกเรียกใช้ แต่ฉันไม่เคยเห็นการบันทึกในคอนโซลเลย?

ฉันไม่แน่ใจว่าฉันทำผิดอะไร

แก้ไข

ฉันก็ได้ลองเช่นกัน

getStoreData {
    forkJoin(
      this._store.pipe(select('userInfo')),
      this._store.pipe(select('xberts')),
      this._store.pipe(select('tasks'))
    ).subscribe(res => console.log(res));
}

แต่ยังคงเป็นปัญหาเดิม ไม่มี console.log()

ความช่วยเหลือใด ๆ ก็จะได้รับการชื่นชม!

คำตอบ #1

ฉันคิดว่าคุณจำเป็นต้องสมัครสมาชิก ลองใช้สิ่งนี้ดู:

getStoreData() {
    combineLatest(
        this._store.select('userInfo'),
        this._store.select('cats'),
        this._store.select('dogs')
    ).pipe(filter(e => !e.includes(null)),tap(([userInfo, cats, dogs]) => console.log(userInfo, cats, dogs))
    .subscribe()
}

หรือ

ngOninit() {
   this.getStoreData().subscribe()
}

คำตอบ #2

คุณสามารถใช้ forkJoin สำหรับสถานการณ์ของคุณได้

ตัวอย่าง :

   forkJoin(
            this.store.pipe(select('userInfo')),
            this.store.pipe(select('cats')),
            this.store.pipe(select('dogs'))
        ).subscribe(res => { });

อะไรประมาณนี้

export const selectUser = createSelector(
    userState,
    state => state.user
);

บทความที่เกี่ยวข้อง