Angular 在可观测生命周期中保持变量
如何在整个可观察的生命周期中保留scriptId? 如果我尝试用不同的ID运行这段代码两次,sId-var将在observable内部发生变化,并将破坏代码Angular 在可观测生命周期中保持变量,angular,typescript,rxjs,Angular,Typescript,Rxjs,如何在整个可观察的生命周期中保留scriptId? 如果我尝试用不同的ID运行这段代码两次,sId-var将在observable内部发生变化,并将破坏代码 SendScript (event, scriptId) { //THINGS HAPPEN...`enter code here` //Setting the id of the script let sId = scriptId; <------ // This is changing eve
SendScript (event, scriptId) {
//THINGS HAPPEN...`enter code here`
//Setting the id of the script
let sId = scriptId; <------
// This is changing every time i send the script
// so later on in my observable this variable changing and breaking the
// uniqness of the script.
//How can I do this correctly to use this id all the observable life and
//it completes ?
this.scriptObs$ = from(scriptLinesObject)
.pipe(
concatMap((SL: ScriptLine) => {
// more code here
//I want to use the id here! <------
if(something) {
return x;
}
else if(somethingElse) {
return y;
}
}),
).subscribe(
(res: any) => {
// more code here
//I want to use the id here! <------
},
(err) => { },
() => {
// more code here
//I want to use the id here! <------
},
);
}
}
SendScript(事件,脚本ID){
//事情发生了……`在这里输入代码`
//设置脚本的id
设sId=scriptId{
//这里有更多代码
//我想在这里使用id{
//这里有更多代码
//我想在这里使用id!{},
() => {
//这里有更多代码
//我想在这里使用id!您不必,sId
值已经保存在每个SendScript()
函数调用中,arrow函数帮助您将上下文保存在绑定到SendScript()
函数的可观察范围内,因此sId
值总是存储在每个SendScript()中并确定其范围
函数调用:
SendScript (event, scriptId) {
...
let sId = scriptId;
...
this.scriptObs$ = from(scriptLinesObject)
.pipe(
concatMap((SL: ScriptLine) => {
console.log(sId)
if(something) {
return x;
}
else if(somethingElse) {
return y;
}
}),catch
).subscribe(
(x) => {
console.log(sId)
},
(err) => { },
() => {
console.log(sId)
},
);
}
}
此外,由于您使用concatMap(),请确保其中返回的x和y是可观察的。您不必在每个SendScript()函数调用中保留sId
值,箭头函数可帮助您将可观察范围内的上下文绑定到SendScript()
函数,因此在每个SendScript()函数调用中总是存储sId
值并确定其作用域:
SendScript (event, scriptId) {
...
let sId = scriptId;
...
this.scriptObs$ = from(scriptLinesObject)
.pipe(
concatMap((SL: ScriptLine) => {
console.log(sId)
if(something) {
return x;
}
else if(somethingElse) {
return y;
}
}),catch
).subscribe(
(x) => {
console.log(sId)
},
(err) => { },
() => {
console.log(sId)
},
);
}
}
此外,由于您使用的是concatMap(),请确保其中返回的x和y是可观察的。如果需要维护变量,请给它一个更大的范围,而不是局部范围如果需要维护变量,请给它一个更大的范围,而不是局部范围