执行后不从订阅者返回真值,它总是返回默认值 false
Not returning the true value from subscriber after execution its always returning default value false
在执行 prefillLoginId 时,我总是得到 false(默认值),即使订阅中的每个代码都在执行。
请帮助我 return 真正的价值。
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 中的代码在您的方法 returning 状态之后执行,并且当它 returning 时它的值为 false。您应该将方法更改为 return 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));
在执行 prefillLoginId 时,我总是得到 false(默认值),即使订阅中的每个代码都在执行。 请帮助我 return 真正的价值。
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 中的代码在您的方法 returning 状态之后执行,并且当它 returning 时它的值为 false。您应该将方法更改为 return 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));