我有一个应用程序,要求某些情况下使用非Angular JavaScript。为了触发Angular组件中的动作,我将向下回调传递给非Angular组件。触发回调后,可观察对象将在Angular组件上运行(执行http调用)。这行得通,但我唯一遇到的难题之一就是以某种方式使从该可观察到的返回的数据传递回非Angular组件。我的实际应用程序相当复杂,因此我为简化得多的版本创建了Stackblitz,以使其更容易查看自己在做什么。
这对我来说很棘手,因为GET
调用doStuff
是异步的,所以我不能只返回结果。我对如何在纯Angular应用程序中解决此问题有一些想法...但是我不确定在Angular组件和非Angular组件之间共享数据时如何实现这一点。
app.component.ts:
export class AppComponent {
constructor(private http: HttpClient){}
doStuff() {
let randomNum = this.getRandomInt(2); // Simulate different http responses
this.http.get<any>(`https://jsonplaceholder.typicode.com/todos/${randomNum}`).subscribe(x => {
if (x === 1) {
// Here is where I want to share data with the non-Angular component
console.log(x.id);
} else {
// Here is where I want to share data with the non-Angular component
console.log(x.id);
}
});
}
ngOnInit() {
var x = new NonAngularComponent(this.doStuff.bind(this));
}
private getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max)) + 1;
}
}
NonAngularComponent.ts:
export class NonAngularComponent {
constructor(private onSave: () => void) {
this.init()
}
init() {
const newElement = document.createElement('button');
newElement.innerHTML = 'Click';
newElement.addEventListener('click', () => {
this.onSave(); // Works, but now I need to do something with the results of doStuff()
});
document.getElementById('foo').append(newElement);
}
}
任何建议将不胜感激。
如果要在Angular组件中产生一些副作用,最好Observable
从doStuff()
方法中返回并使用tap
operator:
doStuff() {
let randomNum = this.getRandomInt(2);
return this.http.get<any>(`https://jsonplaceholder.typicode.com/todos/${randomNum}`).pipe(tap(x => {
if (x === 1) {
// Here is where I want to share data with the non-Angular component
console.log(x.id);
} else {
// Here is where I want to share data with the non-Angular component
console.log(x.id);
}
}));
}
非角度组件
newElement.addEventListener('click', () => {
this.onSave().subscribe(res => {
// do whatever you want
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句