也许我想念一些东西。我找不到有关Observable及其语法的简单教程。我正在使用Angular,我在更改“程序”输入字段值时调用getCampaigns()
函数,以更新广告系列输入字段的自动完成列表。Please refer the image for visual description
当前场景:
当我更改“程序”输入字段值而不是更新输入的广告系列的自动完成列表时,它将新值与以前的自动完成列表值连接起来:有关详细信息,请参见以下示例:
程序值:P1
广告系列的自动填充值为:[C1,C2,C3]。
程序值:P2
广告系列的自动填充值是:[C4,C5,C6]。
当我将Program的值从P1更改为P2时,自动完成列表会串联起来: [C1,C2,C3,C4,C5,C6]
仅查看P2广告系列列表值。
期望:
每次用户更改程序值时,自动完成列表都会刷新,并且仅显示与新程序值相关联的广告系列。
请在下面找到代码:
filteredPrograms: Observable<string[]>;
filteredCampaigns: Observable<string[]>;
ngOnInit() {
//Filters program when user typed
this.filteredPrograms = this.taskDetailForm.get('program').valueChanges
.pipe(
startWith(''),
map(value => this._filter(this.programs, value))
);
//Filters campaigns when user typed
this.filteredCampaigns = this.taskDetailForm.get('campaign').valueChanges
.pipe(
startWith(''),
map(value => this._filter(this.campaigns, value))
);
}
//Get Autocomplete list of campaigns
getCampaigns(){
let selectedProgram = this.taskDetailForm.get('program').value;
this.deliverablesService.getCampaigns(selectedProgram).valueChanges()
.subscribe(campaigns => {
this.campaignRef = campaigns;
this.campaignRef.forEach(campaign => {
if(!this.campaigns.includes(campaign.campaign_name))
this.campaigns.push(campaign.campaign_name)
})
})
}
HTML代码:
<div class="mat-form-field-wrapper">
<mat-form-field appearance="outline">
<mat-label>Program</mat-label>
<input formControlName="program"
matInput
[matAutocomplete]="auto"
(change)="getCampaigns()" >
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredPrograms | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
<mat-error>Invalid Program Name</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="mr-0">
<mat-label>Campaign</mat-label>
<input formControlName="campaign"
matInput
(change)="getDeliverables()"
[matAutocomplete]="auto1">
<mat-autocomplete #auto1="matAutocomplete">
<mat-option *ngFor="let campaign of filteredCampaigns | async" [value]="campaign">
{{campaign}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
预先感谢!
答案 0 :(得分:0)
如果我对您的理解正确,则可能要使用switchMap
运算符。这可能是一个潜在的例子:
this.filteredCampaigns = this.taskDetailForm.get('program').valueChanges.pipe(
switchMap(()=> {
return this.taskDetailForm.get('campaign').valueChanges.pipe(
startWith(''),
map(value => this._filter(this.campaigns, value))
);
})
);
答案 1 :(得分:0)
感谢Evaldas付出的努力。但是我发现自己做错了。
我只需要清除campaigns
阵列中的广告系列即可。
getCampaigns(){
let selectedProgram = this.taskDetailForm.get('program').value;
this.deliverablesService.getCampaigns(selectedProgram).valueChanges()
.subscribe(campaigns => {
this.campaignRef = campaigns;
this.campaigns = [];
this.campaignRef.forEach(campaign => {
if(!this.campaigns.includes(campaign.campaign_name))
this.campaigns.push(campaign.campaign_name)
})
})
}
在推送新值之前添加了this.campaigns = [];
。