2 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您想在 Angular 組件中產(chǎn)生一些副作用,最好Observable從您的doStuff()方法返回并使用運(yùn)算符: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貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
我認(rèn)為最簡(jiǎn)單的解決方案是在 AppComponent 中簡(jiǎn)單地?fù)碛幸粋€(gè) NonAngularComponent 實(shí)例
this.nonAngularComponent = new NonAngularComponent(this.doStuff.bind(this));
在回調(diào)中,只需從 NonAngularComponent 中調(diào)用您想要的方法,如下所示:
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);
}
和控制臺(tái)輸出:
添加回答
舉報(bào)