-1

app.component.html

    {{loading_message}}

app.component.ts

 @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css'],
     providers: [ApiBridgeService]
 })
 export class AppComponent {
     title = 'app works!';
     loading_message: String;

     constructor() {
         this.loading_message = "Init";
         setInterval(this.change_loading_message, 1000)
    }

     change_loading_message() {
        this.loading_message = "Executing"
     }
}

In html it always displays Init

Expected result :

It should display executing after a 1000ms.

bashIt
  • 1,006
  • 1
  • 10
  • 26

1 Answers1

1

If you are using Observables (which you should), it is quite trivial to achieve that. I recommend an ngOnInit to 'kickoff' the observable at the point the component is initialized.

 @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css'],
     providers: [ApiBridgeService]
 })
 export class AppComponent {
     title = 'app works!';
     loading_message: String;

     constructor() {
         this.loading_message = "Init";
     }

     ngOnInit(){
       Observable
           .empty()      //this is optional
           .delay(1000)  //delay for 1000ms
           .subscribe(()=>{  //subscribe to the observables!
              this.loading_message = "Executing"  //change your message!
           }); 
     }
}

To use the .delay() operator, you will need to import it:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/delay';

Note that the .empty() is optional. I like to use a .empty() to explicitly indicates that this observables is not going to return anything. If you are using .empty, you need to import it as well:

import 'rxjs/add/observable/empty`

More detailed explanation on Observables.delay()

CozyAzure
  • 8,280
  • 7
  • 34
  • 52