Skip to content

Web Worker => Behaviorsubject => Subscribe = Not updated on the component view #19334

@efa2000

Description

@efa2000

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x ] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Service star Web Worker and listen message:

@Injectable()
export class MarketdataService {
  private worker: Worker;
  public tiketsChange: BehaviorSubject<any>;

    constructor() {
      this.tiketsChange = new BehaviorSubject(0);
    }

    public loadWorker(name:string){
      this.tiketsChange.next(100);
      this.worker = new Worker('/assets/workers/'+name+'.js');
      this.worker.onerror = (err)=>{
        console.error(err);
      };
      this.worker.onmessage = (e)=>{
         this.tiketsChange.next(200);
      };
    }
}

Component:

export class ToolbarComponent implements OnInit {
  public last : number;
  private sub: Subscription;

    constructor(public md:MarketdataService) { 
    }

    ngOnInit() {
      this.sub=this.md.tiketsChange.subscribe(tikets=>{
        this.last = tikets;
        console.log(this.last);
      })
     this.md.loadWorker('test');
  }
}

View HTML:

<p>{{ last }} </p>

When comonent init:

Console => 0
View => 0

When worker start loading:

Console => 100
View => 100

When worker send message:

Console => 200
View => 100
!! View NOT Update

Workaround

In component use ngZone.run() then all OK

ngOnInit() {
    this.sub=this.md.tiketsChange.subscribe(tikets=>{
        this._ngZone.run(()=>{
          this.last = tikets;
        })
        console.log(this.last);
      }) 
  }

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


@angular/cli: 1.4.1
node: 8.5.0
os: linux x64
@angular/animations: 4.4.3
@angular/common: 4.4.3
@angular/compiler: 4.4.3
@angular/core: 4.4.3
@angular/flex-layout: 2.0.0-rc.1
@angular/forms: 4.4.3
@angular/http: 4.4.3
@angular/platform-browser: 4.4.3
@angular/platform-browser-dynamic: 4.4.3
@angular/router: 4.4.3
@angular/cli: 1.4.1
@angular/compiler-cli: 4.4.3
@angular/language-service: 4.4.3
typescript: 2.3.4

Browser:
- [x] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: coreIssues related to the framework runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions