我有一个应用程序要求我为某些事情使用非 Angular JavaScript。为了在 Angular 组件中触发一个动作,我将一个回调传递给非 Angular 组件。触发回调时,可观察对象会在 Angular 组件上运行(执行 http 调用)。这行得通,但我遇到的唯一难题是以某种方式从该可观察对象返回的数据传递回非 Angular 组件。我的实际应用程序相当复杂,因此我创建了一个简化得多的Stackblitz版本,以便更容易看到我在做什么。
这对我来说很棘手,因为GET调用doStuff是异步的,所以我不能只返回结果。我对如何在纯 Angular 应用程序中解决这个问题有一些想法......但我不确定在 Angular 组件和非 Angular 组件之间共享数据时如何实现这一点。
应用程序组件.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;
}
}
非角度组件.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);
}
}
任何建议将不胜感激。
桃花长相依
开心每一天1111
相关分类