我试图通过将其存储到全局变量中来访问订阅方法中收到的数据,当我尝试控制台记录它时,我只看到“未定义”
我尝试在 HTML 文档中写入数据,我可以在其中看到预期的输出,但从不同的函数访问相同的变量似乎不起作用
我正在研究 Angular 和 TS,这是代码片段:
import ruleChain from './ev-template/rule_chains/main.json';
export class AComponent extends PageComponent {
apidata: any;
constructor(protected store: Store<AppState>,
private ruleChainService: RuleChainService) {
super(store);
}
createRuleChain(): any {
let requestBody: any = ruleChain.ruleChain;
this.ruleChainService.saveRuleChain(requestBody).subscribe(
(data) => {
this.apiData = data.id.id;
console.log(this.apiData); // returns data
},
(error) => {
}
);
console.log(this.apiData); // returns undefined
}
installEVTemplate() {
this.evCreateRuleChain();
console.log(this.apiData); // returns undefined
}
}
其中 installEVTemplate 由 HTML 文档上的按钮触发。
我尝试了 pipeline、map、Observer 和 Observable 方法,还尝试从 subscribe 方法内返回数据,也是一个变量,然后在 subscribe 外部但在 createRuleChain 函数内返回该变量,但即使这样也返回 undefined
我是前端开发新手。 非常感谢任何解决此问题的帮助!
要从可观察的值中获取值,您需要订阅。
您未定义,因为该代码在订阅之外运行(它在 api 返回数据之前运行)。
您可以将 installEVTemplate 代码放入订阅中以使用生成的 apiData。
如果您需要一个 api 调用中的数据给另一个 api 调用,则可以使用 RxJ 创建更清晰的流来链接可观察量。不推荐的替代方案是嵌套订阅。
import ruleChain from './ev-template/rule_chains/main.json';
export class AComponent extends PageComponent {
// observable
apiData$ = this.ruleChainService
.saveRuleChain(ruleChain.ruleChain)
.pipe(
map(data => data.id.id)
);
// rest of comp
someMethod() {
apiData$.pipe(
// use apiData in another api call
switchMap(apiData => this.someService.method(apiData))
).subscribe(someData => {
//
})
}
}