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



我有一个fetch-person组件,它在perList: Observable<Person[]>中加载一些数据。然后在第一次数据不加载到this.personList(从登录页面到取人组件RouterModule.forRoot([{ path: '', redirectTo: '/fetch-person', pathMatch: 'full'})),然而,当我点击其他页面并点击标题<a class="nav-link text-dark" [routerLink]='["/fetch-person"]'>Fetch Person</a>后,它会将数据返回到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());

}

最新更新