Recently, I started working with the Angular framework and encountered an issue while developing a basic data retrieval feature from a component using a service. I had already set up a web service that returns specific data for an ID (wwid
). The function called via the service (app.service
) from the component (queueSearch.component
) triggers a GET
request. Although the data is successfully retrieved within the service, it doesn't update the variable associated with the component (waittime
) immediately. Strangely, the variable only gets updated after a second call (requiring me to click the search button twice to reflect the change on the HTML). How can I ensure that it updates with a single click?
app.service.ts
searchWWID(wwid: number)
{
console.log("from app service wwid: " + wwid.toString());
this.http.get("http://localhost:3000/api/list/" + wwid).subscribe(Data =>{
if(Data != null)
{
this.waitingTime = JSON.stringify(Data)
}
else
{
this.waitingTime = "";
}
//this gets updated instantaneously and prints
console.log(this.waitingTime);
});
return this.waitingTime;
}
}
queueSearch.component.ts
searchWWID()
{
if(isNaN(Number(this.wwid)))
{
console.log("not a number");
}
else
{
if(this.wwid.toString().length !== 8)
{
console.log("should be eight digits")
}
else
{
//this(waittime) only gets updated after every second call to this function
this.waitTime = this.AppService.searchWWID(Number(this.wwid))
}
}
}
queueSearch.component.html
<h1>{{title}}</h1>
<div style ="text-align:center">
<form>
<input type="text" class="form-control" placeholder="enter wwid"
[(ngModel)]="wwid" name="wwid" id="searchWWID">
<button class="btn btn-primary" id="submitButton"
(click)=searchWWID()>Submit</button>
</form>
</div>
<h2>waiting time: {{waitTime}}</h2>
Desired Outcome: Update waittime
in HTML instantaneously after calling searchWWID()
.
Current Outcome: waittime
only updates after every second function call.