question:
According to the requirements in the project, a drop-down box needs to be designed to provide real-time suggestions based on the content when entering. Here we use the following components,
<p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"> </p-autoComplete>
Because we need to query the background in real time based on the input content, if each change is passed to the background, it will be too resource-consuming and not user-friendly. For this reason, we use angular request anti-shake processing, the code is as follows.
packages$: Observable<NpmPackageInfo[]>; private searchText$ = new Subject<string>(); search(packageName: string) { $.next(packageName); } ngOnInit() { $ = $.pipe( debounceTime(500), distinctUntilChanged(), switchMap(packageName => (packageName, )) ); }
The functions are as follows:
debounceTime(500) - Wait until the user stops input (in this example, stops 1/2 second).
distinctUntilChanged() - Wait until the search content changes.
switchMap() - Sends a search request to the service.
But when we use it, we find that when the first request is initialized, the service method will not be called. The error code is as follows:
private searchText$ = new Subject<string>(); packages$: Observable<InstrumentAlias[]>; ngOnInit() { // Create observable objects$ = $.pipe( debounceTime(500), distinctUntilChanged(), switchMap(packageName => (packageName)) ); } $.next(); $.subscribe((instrumentAliases: Array<InstrumentAlias>) => { = instrumentAliases; }, () => { ('get instrumentAliases error'); });
searchText$ is a sequence containing all the values entered by the user into the search box. It is defined as the Subject object of RxJS, which means it is a multicast Observable. At the same time, you can also call next(value) to generate the value. In the above wrong code, because we called the next method first, although the value was generated, but it has not been subscribed yet, so the first value will not initiate a request to the background. Later, because we have subscribed to this thing, the request after the first request has effect.
Results method:
Subscribe during initialization, so that in the future, we only need to use next to pass the value, and the object we have subscribed will automatically trigger the background request.
Summarize:
When writing functions, the code is simply copied and pasted, and there is no real understanding of the design mechanism of the observer of angular. This error deepens the understanding of the observer of angular.
The above is the problem of the first request for anti-shake processing of Angular requests introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!