typescript - Angular 2: ako správne zmeniť premennú šablóny cez službu?


Nemôžem dynamicky meniť stav HTML elementu pomocou nejakej vlastnosti komponentu.

@Component({
    selector: 'home-page',
    templateUrl: 'home.component.html',
    styleUrls:['home.component.scss'],
    providers:[AuthService]

})

export class HomeComponent  implements OnInit {
    public isAuth: boolean;

    constructor(private auth: AuthService) {

   ngOnInit() {
      this.isAuth = this.auth.temp;
      console.log(this.isAuth);
  }
}

Moja AuthService je tu:

@Injectable()
export class AuthService {

    public activeUser:ReplaySubject<any> = new ReplaySubject();
    dataBoolean$ = this.activeUser.asObservable();

    set signIn(val: boolean) {
        console.log("sign-in");

        Observable.of(val).subscribe
        (
            res => {
                this.activeUser.next(res);
                console.log("SIGNIN >>>>> ", res);
                this.temp = res;
            }
        );
        console.log("temp", this.temp);
    }
}

OK, keď kliknem na tlačidlo signIn(), kód funguje správne: vidím výstup v konzole zo služby a potom z komponentu.

Ale v mojej šablóne mám toto:

<button [disabled]="isAuth">Pull</button>

Považujem za to, že keď Observable vydá novú hodnotu, dostanem ju v komponente a nová vlastnosť komponentu by sa mala okamžite zobraziť v šablóne.

Dokonca aj týmto spôsobom:

setInterval(() => {
            this.isAuth = !this.isAuth;
            console.log(this.isAuth);
        }, 2000);

Tlačidlo nemôže zmeniť svoj stav.

Ale to nie je pravda alebo robím niečo zle.

Odpoveď č. 1

Angular 2 detektor zmien používa zóny na detekciu zmien. Napríklad, ak chcete použiť časovač (ako setInterval), musíte to urobiť týmto spôsobom:

setInterval(() => {
     this.isAuth = !this.isAuth;
     console.log(this.isAuth);
     this.cd.detectChanges();
}, 2000);

Čo je vlastnosť this.cd? Je to injektovaný ChangeDetectorRef:

constructor(private cd : ChangeDetectorRef) {}

Ale prečo to musíte robiť? Pretože v Angular 2 sú detektory zmien zodpovedné za informovanie Ng2, kedy má aktualizovať zobrazenie.

Tam si o tom môžete veľa prečítať:

http://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html