Paulo Henrique Junior
Paulo Henrique Junior

Reputation: 179

Calling services in Angular

Imagine I have a private property in my component.
Is it possible, to assign a value inside a then call to an API and after using it over my component? i.e:

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage extends BaseComponent {
    private currentWebDate: string = ""

    ionViewDidEnter(){
       this.getDateAndTime()
    }

    const getDateAndTime = () => {
        this.timeService.getDateAndTime()
           .then((time: Time) => {
                 this.currentWebDate = time.currentDateString
           })
    }

    //and the reuse variable currentWebDate outside subscribe.
}

As I tried, the currentWebDate variable is just possible to manipulate inside the then call not over the component. Any ideas why?

Upvotes: 0

Views: 223

Answers (2)

Hoang Subin
Hoang Subin

Reputation: 7400

This is old question in programming. You need to understand asynchronous and synchronous in programming to answer this question.

in my point of view, I do not think "the currentWebDate variable is just possible to manipulate inside the then call not over the component" is RIGHT.

You cannot get the value because before ionViewDidEnter your method will not call then the variable have no value. Plus, inside ionViewDidEnter you still cannot get value like below:

ionViewDidEnter(){
  this.getDateAndTime()
  console.log(this.currentWebDate) // no value
}

Because it is about wait time issue. at the time you print the value on the lifecycle, the response still not coming.

I suggested you 3 solutions:

  1. use rxjs to handle this issue. You can read this article to have some idea how to use rxjs to compose and manage your data

  2. use state management. I suggested use ngxs that is more easier than ngrx(this one you need to understand redux pattern)

  3. angular resolve in case that you re not familiar with rxjs and state management.

Upvotes: 1

Pablo Palacios
Pablo Palacios

Reputation: 2947

Based on your code, you might be missing the (1) injection of the service using the constructor, (2) use getDateAndTime as a method of the class, and (3) public currentWebDate if you what it to be available for the template.

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage extends BaseComponent {
    public currentWebDate = ""; //<<<(3)

    constructor(private timeService: TimeService){ //<<<(1)
    }

    ionViewDidEnter(){
       this.getDateAndTime()
    }

    private getDateAndTime(): void{ //<<<(2)
        this.timeService.getDateAndTime()
           .then((time: Time) => {
                 this.currentWebDate = time.currentDateString
           })
    }
}

Upvotes: 1

Related Questions