我有这个简单的服务,它是两个模块中的provider
:
@Injectable()
export class PlatformPickerService {
platforms: string[] = [
'macOS', 'Linux', 'Windows'
];
public platform: string;
constructor() {
this.platform = this.platforms[1];
}
public getPlatform(): string {
const platform = localStorage.getItem('platform');
return platform == null ? this.platform : platform;
}
public setPlatform(platform: string) {
this.platform = platform;
localStorage.setItem('platform', platform);
}
}
不幸的是,我无处使用它获得了所选择的价值。在模块外部使用它只给出默认值,在其模块中使用它不会给出任何值。
终于搞定了:https://angular-aru94g-w6qy21.stackblitz.io(edit)
主要变化是:
updateService(event: any) {
if (event.value != null) this.platformPickerService.setPlatform(event.value);
}
<mat-form-field>
<mat-select placeholder="Platform" shouldLabelFloat="false"
[(ngModel)]="platformSelectd"
(selectionChange)=updateService($event)>
<mat-option *ngFor="let platform of platformPickerService.platforms"
[value]=platform>
{{ platform }}
</mat-option>
</mat-select>
</mat-form-field>
PlatformPickerService
(app.module)现在是时候尝试再次重写setter / getters,看看它是否有效(setPlatform
to set platform
)= 3
服务是注射器范围内的单件。将PlatformPickerService定义为应用程序模块或根模块中的提供程序,并将其设置为单例服务。这将是应用程序范围的单例服务。
好的,你的PlatformPickerComponent问题。您必须将所选值发送到updateService。
请检查sample app和demo。
PlatformPickerService中设置的默认平台值,只要更改它,它就会在下拉框中反映为选定值。
constructor() {
this.platform = this.platforms[4];
}
你错过了PlatformPickerComponent
中的双向绑定将FormsModule
的导入添加到PlatformPickerModule
并更改PlatformPickerComponent
如下:
<mat-form-field>
<mat-select placeholder="Platform" shouldLabelFloat="false" [(ngModel)]="platform">
<mat-option *ngFor="let platform of platformPickerService.platforms"
[value]="platform">
{{ platform }}
</mat-option>
</mat-select>
</mat-form-field>
import {AfterViewInit, Component, OnInit} from '@angular/core';
import {PlatformPickerService} from './platform-picker.service';
@Component({
selector: 'platform-picker',
templateUrl: './platform-picker.component.html',
styleUrls: ['./platform-picker.component.css']
})
export class PlatformPickerComponent implements OnInit, AfterViewInit {
private _platform: string;
constructor(public platformPickerService: PlatformPickerService) {
}
ngOnInit() {
this._platform = this.platformPickerService.getPlatform();
}
ngAfterViewInit() {
}
get platform(): string {
return this._platform;
}
set platform(value: string) {
if (value != null) {
this.platformPickerService.setPlatform(value);
this._platform = value;
}
}
}
我对您现有的代码进行了一些更改。如果您使用双向绑定,则可以跳过ngModelChange,否则使用单向绑定和ngModelChange,如下所示。
<mat-form-field>
<mat-select [ngModel]="selected" (ngModelChange)="updateService($event)" placeholder="Platform" shouldLabelFloat="false" [(value)]="selected">
<mat-option *ngFor="let platform of platformPickerService.platforms"
[value]="platform">
{{ platform }}
</mat-option>
</mat-select>
</mat-form-field>
并按如下方式更新Service函数
updateService(newPlatform) {
console.log(newPlatform);
if (newPlatform != null) {
this.selected = newPlatform;
this.platformPickerService.setPlatform(this.selected);
}
}