【发布时间】:2018-09-04 20:31:55
【问题描述】:
所以我有一个基础组件,在它的构造函数中我有一个 observable,一旦它在另一个验证用户数据的组件中被接收到,就可以获取一个值。但是,当尝试在子类中获取此值时,数据到达时未定义。在我遇到问题的代码下方:
我的观察者:
@Injectable()
export class ObservableUsuario implements ObservableUtil {
subject = new Subject<any>();
setUsuario(variable: any) {
this.subject.next({ text: variable });
}
clearUsuario() {
this.subject.next();
}
getUsuario(): Observable<any> {
return this.subject.asObservable();
}
这里 observable 设置了:
getValue = (refresh: boolean = true) => cacheable(
() => this.http.get(`${environment.apiEndpoint}/api/Get/Value`, headers()).map(res => {
this.observableUser.setUsuario(res.json());
return res.json();
}),
);
基础组件:
//more code
perfilLotado: any;
constructor(
public observableUser: ObservableUsuario
) {
this.observableUser.getUsuario().subscribe(
perfil => this.perfilLotado = perfil.text.lotacaoDTO[0].perfilDTO[0].nome);
}
//more code
子组件:
export class BaseListComponent extends BaseComponent {
NgOnInit(){}
validAction(situacao: number): any {
//Here appearer like undefined...
console.log(this.perfilLotado);
if (this.sistema.situacaoRestric[situacao] != undefined) {
this.showMsg('warn', 'Mensagem de Alerta', this.sistema.situacaoRestric[situacao]);
return false;
} else if (this.sistema.situacaoRestric[situacao] == undefined && this.sistema.perfilRestrict[this.perfilLotado] != undefined) {
this.showMsg('warn', 'Mensagem de Alerta', this.sistema.perfilRestrict[this.perfilLotado]);
return false;
} else if (this.sistema.situacaoRestric[situacao] == undefined && this.sistema.perfilRestrict[situacao] == undefined) {
return true;
}
}
换句话说,我的问题是将我的 observable 传递的值加载到子组件类。 注意:据我了解,它是加载的最后一个组件,我怎样才能让它在屏幕的其他组件之前加载?
【问题讨论】:
-
尝试将订阅 observable 的代码移动到 ngOnInit
-
谁调用“getValue()”以及何时调用?
-
@Ricardo,我尝试但不工作......
-
@DiabolicWords 在基础组件的构造函数中。加载时。
-
在我看来,validAction 应该从 perfilLotado 的 observable 中读取,你应该在那里订阅和管理你的逻辑
标签: angular observable angular5