我正在尝试在我的服务中创建一个变量,只要我注入这个服务就可以访问它。但是,我无法填充我的login$
BehaviorSubject类型。我检查了this和this,但我很难理解它是如何工作的。
组件
this.loginService.login = user.value.username; // OK
this.loginService.pass = user.value.password; // OK
this.loginService.emitLogin(user.value.username); // UNDEFINED - user.value.username is input field of form group
login服务
export class LoginService {
public login: string;
public pass: string;
public login$ = new BehaviorSubject(this.login);
emitLogin(value: string) {
this.login$.next(value);
}
constructor(private http: Http) { }
}
另外,我想在login$
中使用DriverService
。这是我到目前为止所做的事情:
DriverService
export class DriverService {
private login;
constructor(private http: Http, private loginService: LoginService) {
this.loginService.login$.subscribe(value => {
console.log(value);
this.login = value;
});
}
}
如何正确填充并使其可用于其他服务?
由于
答案 0 :(得分:0)
BehviorSubject always initialized with some value but in your code your initializing with variable definition.
public login: string;
public login$ = new BehaviorSubject(this.login);
do something like this
public login$ = new BehaviorSubject('');
emitLogin(value: string) {
this.login$.next(value);
}