我有变量" choosenModels"在我的服务中,这是在两个组件中使用的:app.component和他的子组件gallery.component。当我点击按钮时,那应该改变" choosenModels"的值,但是这个改变只能在他自己的组件中看到。如何让其他组件可见?这是代码:
Models.service.ts:
@Injectable()
export class ModelsService {
private _choosenModels: string = 'female';
_choosenModelsUpdate = new EventEmitter<string>();
getChoosenModels() {
return this._choosenModels;
}
setChoosenModels(value: string) {
this._choosenModels = value;
this._choosenModelsUpdate.emit(this._choosenModels);
}
}
关于父子关系的两个组成部分。父App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ ModelsService ],
})
export class AppComponent {
choosenModels: string = 'test';
constructor(private _modelsService: ModelsService) {}
ngOnInit() {
this.choosenModels = this._modelsService.getChoosenModels();
this._modelsService._choosenModelsUpdate.subscribe(
(choosenModels) => {
this.choosenModels = this._modelsService.getChoosenModels();
}
);
}
onChangeModelsTeamClick(value: string) {
console.log(value);
this._modelsService.setChoosenModels(value);
}
}
App.component.html:
<nav class="footer__nav">
<button
class="button"
(click)="onChangeModelsTeamClick('female')"
>
<div class="button__description">Modelki</div>
<i class="button__sign button__sign--female"></i>
</button>
<button
class="button button--male"
(click)="onChangeModelsTeamClick('male')"
>
<i class="button__sign button__sign--male"></i>
<div class="button__description button__description--male">Modele</div>
</button>
</nav>
子组件:gallery.component.ts:
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.scss'],
providers: [
ModelsService,
],
})
export class GalleryComponent implements OnInit {
choosenModels: string;
constructor(private _modelsService: ModelsService) {}
ngOnInit() {
this.choosenModels = this._modelsService.getChoosenModels();
this._modelsService._choosenModelsUpdate.subscribe(
(choosenModels) => {
this.choosenModels = this._modelsService.getChoosenModels();
}
);
}
onChangeModelsTeamClick(value: string) {
this._modelsService.setChoosenModels(value);
}
}
gallery.component.html:
<nav class="navigation">
<button
class="button"
(click)="onChangeModelsTeamClick('female')"
[ngClass]="{'active': choosenModels=='female'}"
>
MODELKI
</button><!--
--><button
class="button"
(click)="onChangeModelsTeamClick('male')"
[ngClass]="{'active': choosenModels=='male'}"
>
MODELE
</button><!--
--><button
class="button"
(click)="onChangeModelsTeamClick('premium')"
[ngClass]="{'active': choosenModels=='premium'}"
>
PREMIUM
</button>
</nav>
答案 0 :(得分:1)
providers: [
ModelsService,
]
这告诉Angular创建一个ModelsService实例,专用于每个组件实例(及其子组件,递归)。由于你的两个组件都有,所以每个组件都有自己的服务实例。
其他问题:
choosen
应为chosen