观察者订阅不会第一次加载,不会在第一次加载到组件时触发

Observer subscribe doesn't load first time, not firing on first load to Component

我有一个 fetch-person 组件,它在 perList: Observable<Person[]> 中加载一些数据。然后第一次数据没有加载到 this.personList(从登录页面到 fetch-person 组件 RouterModule.forRoot([{ path: '', redirectTo: '/fetch-person', pathMatch: 'full'}) 但是,在我点击其他页面并点击 header <a class="nav-link text-dark" [routerLink]='["/fetch-person"]'>Fetch Person</a>,它会 return 数据到 this.personList。我想出了我的代码(代码在 Typescript 中):

如何从第一次加载中获取数据?

fetch-person.component.ts

@Component({
  selector: 'app-fetch-person',
  templateUrl: './fetch-person.component.html',
  styleUrls: ['./fetch-person.component.css']
})

@Injectable()
export class FetchPersonComponent implements OnInit {
    [x: string]: any;

  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;

  SearchpersonForm: FormGroup;
  loading$: Observable<Boolean>;
  error$: Observable<Error>
  public perList: Observable<Person[]>;
  personList: Person[];
  pagedList: Person[] = [];
  breakpoint: number = 3; 
  length: number = 0;
  pageSize: number = 25;  //displaying three cards each row
  pageSizeOptions: number[] = [5, 10, 25, 100];

  //, private decimalPipe: DecimalPipe
  constructor(private _fb: FormBuilder, private store: Store<AppState>) {
    this.SearchpersonForm = this._fb.group({
      name: ['', [Validators.required]]
    })
  }
  
 ngOnInit() {
      this.store.dispatch(FetchPerson());
     this.perList = this.store.pipe(select(getPersons));
     this.perList.subscribe(result => { this.personList = result; } );<-- **there is no data for the first load from redirectTo: '/fetch-person', however, there are some data after second load from [routerLink]='["/fetch-person"]'**
      this.pagedList = this.personList;
     this.length = this.personList.length;
 }

您的代码存在的问题是订阅是可观察的并且异步运行。因此,订阅下面的代码在填充变量之前执行。

为了清楚起见,我也会在发送前订阅。

 ngOnInit() {
      this.store.pipe(select(getPersons))
                .subscribe(result => { 
                                      this.personList = result;
                                      this.pagedList = this.personList;
                                      this.length = this.personList.length; 
                                   });

      this.store.dispatch(FetchPerson());
  
 }