2 回答
TA贡献1860条经验 获得超8个赞
如果您想在 Angular 组件中产生一些副作用,最好Observable从您的doStuff()方法返回并使用运算符:tap
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);
}
}));
}
非角度.component.ts
newElement.addEventListener('click', () => {
this.onSave().subscribe(res => {
// do whatever you want
});
});
TA贡献1836条经验 获得超13个赞
我认为最简单的解决方案是在 AppComponent 中简单地拥有一个 NonAngularComponent 实例
this.nonAngularComponent = new NonAngularComponent(this.doStuff.bind(this));
在回调中,只需从 NonAngularComponent 中调用您想要的方法,如下所示:
doStuff() {
let randomNum = this.getRandomInt(2);
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);
this.nonAngularComponent.doSomething(x);
} else {
// Here is where I want to share data with the non-Angular component
// console.log(x.id);
this.nonAngularComponent.doSomething(x);
}
});
}
doSomething方法:
public doSomething(result) {
console.log("Non-Angular component received result", result);
}
和控制台输出:
添加回答
举报