Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

javascript - Angular does not detect changes made from window global function

During the work I encountered a very strange behaviour.

Here is the link for a similar problem: stackblitz

From index.html file I have raised some click event

function createClause(event) {
    Office.context.document.getSelectedDataAsync(
      Office.CoercionType.Text,
      (asyncResult) => {
        window.sendSelectedTextCallback({selectedText: asyncResult.value});
        event.completed();
      });
  }

In the app.component.ts I'm listening to the sendSelectedTextCallback function.

(window as any).sendSelectedTextCallback = (params: any) => {
    clauseCommunicationService.addClause({name: params.selectedText});
};

clauseCommunicationService.addClause method calls next function for a subject.

In some component I'm listening for the changes.

this.clauseAddedSubscription = clauseCommunicationService.clauseAdded$.subscribe(
  (clause) => {
    this.clauses.push(clause);
    console.log(this.clauses);
  }
);

The issue i'm facing is that console.log(this.clauses) command shows me the list updated, but this is not reflected on the UI.

If I'm replacing

(window as any).sendSelectedTextCallback = (params: any) => {
    clauseCommunicationService.addClause({name: params.selectedText});
}

with

setTimeout(() => {
   clauseCommunicationService.addClause({name: 'helloooo'});
 }, 4000);

i can see that the changes are reflected on the UI.

I tried to use ngZone and ChangeDetector features but without success.

question from:https://stackoverflow.com/questions/65830468/angular-does-not-detect-changes-made-from-window-global-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is because the button is outside of angular, so angular doesn't test for change detection on the button so when the button gets clicked it doesn't know something happened. We can add change detection to that button using a @HostListener Stack Blitz example.

export class HelloComponent {
  public elements = [1, 2, 3, 4];

  @HostListener('window:click')
  private onWindowClick() {
    this.cdr.detectChanges();
  }

  constructor(
    @Inject(CommunicationService)
    private communicationService: CommunicationService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit() {
    this.communicationService.elemAdded$.subscribe(elem => {
      this.elements.push(elem);
      console.log(this.elements);
    });
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...