当preillloginid正在执行时,我总是得到false(默认值),即使订阅中的每个代码都在执行。请帮助我返回True值。
private prefillLoginId(currentLoginId: any, cms: any)
{
let status =false;
let patterns = [];
this.subSink.sink = cms.subscribe(content => {
patterns = !!content['ClientSideValidations']['LoginId'] ? content['ClientSideValidations']['LoginId'] : [''];
status = this.patternCheckStatus(patterns, currentLoginId);;
});
return status;
}
private patternCheckStatus(patterns:any,currentLoginId)
{
let patternCheckStatus = false;
let regex: RegExp;
patterns.forEach(x => {
regex = new RegExp(x);
if (regex.test(currentLoginId)) {
patternCheckStatus = true;
}
});
return patternCheckStatus;
}
这是因为这里的异步操作。subscribe中的代码在从方法返回状态后执行,并且当它返回其值为false时执行。你应该改变你的方法,像下面这样返回observable:-
private prefillLoginId(currentLoginId: any, cms: any)
{
let status =false;
let patterns = [];
return cms.pipe(map(content => {
patterns = !!content['ClientSideValidations']['LoginId'] ? content['ClientSideValidations']['LoginId'] : [''];
status = this.patternCheckStatus(patterns, currentLoginId);;
return status;
}));
}
,无论你在哪里调用这个方法,使用它像:-
prefillLoginId.subscribe((status) => console.log(status));