Reputation: 1097
I've seen several posts about this solution, but I cannot put mine working. I have two components (same level) and lots of repeated functions that I want to put in a service. This example method with boolean values, i wrote in the service, the component can acess it, but it doesnt work. Example:
Service:
langSwitch(fr:boolean, eng:boolean) {
if (fr=== true && eng === false) {
fr = false;
eng = true;
} else if (fr === false && eng === true) {
fr = true;
eng = false;
}
}
Component:
engActive=true;
frActive=false;
langSwitch(){
this.local.langSwitch(this.frActive, this.engActive);
}
HTML
<div class="row">
<div class="col-10 text-right">
<h4 (click)="langSwitch
()">FR</h4>
</div>
<div class="col-2 text-left">
<h4 (click)="langSwitch()">EN</h4>
</div>
</div>
Another half/working example @veben
Service:
mathTest( a: number, b: number, c:boolean){
let x = a * b > 0;
if(x){
alert('correct');
c = true;
return alert(a*b)
}
}
Component TS
a:number;
b:number;
c=false
mathTest() {
this.local.mathTest(this.a, this.b, this.c);
}
HTML:
<div class="row">
<input type="text" class="form-control" [(ngModel)]="a">
<input type="text" class="form-control" [(ngModel)]="b">
<button class="btn btn-danger" (click)="mathTest()">Calculate!</button>
<div *ngIf="c" class="alert alert-danger col-md-6 offset-md-3" role="alert">
Hello!
</div>
</div>
With this last code, the math is done, the alerts show up, but not the div based on the c value. I dont get errors, so I have to assume that my logic is wrong..
Upvotes: 0
Views: 65
Reputation: 22322
You are not changing the value of c
in your component but only locally in your service. Try the code below, based on your second example:
Service:
// return true if a * b > 0
mathTest(a: number, b: number): boolean {
return a * b > 0;
}
Component:
a: number = 2;
b: number = 1;
c: boolean = false;
// Controller with service injection
// ...
ngOnInit() {
this.c = this.local.mathTest(this.a, this.b);
}
Upvotes: 1