我正在使用Angular CLI。实际上,我有一项服务。此服务返回变量 answer 。我想在app-component(或变量的dublicate)中使用变量。因此当回答更改时,必须在app-component中看到它。现在我可以看到该变量的初始值,并且看不到更改的回答。
服务:
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
@Injectable()
export class LogInGuardService implements CanActivate {
public answer: boolean;
public i: number = 0;
canActivate() {
let entered = JSON.parse(localStorage.getItem('enteredValue'));
let enteredEmail = entered.email_field;
let enteredPw = entered.password_field;
let guardChange = false;
for (var i = 1; i < localStorage.length; i++) {
let stored = JSON.parse(localStorage.getItem(localStorage.key(i)));
let storedEmail = stored.email_field;
let storedPw = stored.password_field;
if ( enteredEmail == storedEmail ) {
if ( enteredPw == storedPw ) {
this.answer = true;
} else {
alert('Неверный пароль');
this.answer = false;
}
} else {
this.i++;
}
}
if (this.i == localStorage.length-1) {
alert('Пользователя с таким e-mail не существует');
}
return this.answer;
}
constructor() { }
}
应用组分:
import { Component } from '@angular/core';
import { LogInGuardService } from './log-in-guard.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public guardInMain: boolean;
constructor(private loginService: LogInGuardService) {
this.guardInMain = true;
this.guardInMain = !this.loginService.answer;
}
}
答案 0 :(得分:5)
如果您想在服务中存储一些变量,可以使用Observables。
使用BehaviorSubject。主体既是可观察的,也是观察者。所以你可以告诉它有一个新答案,它将通知所有订阅者。
在您的服务中:
answer$ = new BehaviorSubject<string>('');
getAnswer(): Observable<string> {
return this.answer$.asObservable();
}
giveAnswer(answer: string) {
this.answer$.next(answer);
}
请注意,构造函数接受初始值。
您可以设置新答案:
AnswerService.giveAnswer('this is my answer');
您可以在任何地方订阅价值变化:
AnswerService.getAnswer().subscribe(answer => console.log(answer));