Answer the question
In order to leave comments, you need to log in
Why is data from localstorage displayed when switching to another page from 2 times?
I need to pass data when going to another page and immediately display it, I use data transfer thanks to localstorage, but I don't understand why the data is displayed only from 2 times.
This is main.component.ts:
import {Component, Input} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {IMetric} from "./metric";
import {Router} from "@angular/router";
@Component({
selector: 'home-app',
template: `
<div class="box" >
<p class="nameOfTheMetric">Halstead metric</p>
<textarea class="input_text" type="text" [(ngModel)]="code"></textarea>
<button (click)="goCalculate()" class="shine-button">Calculate the metric</button>
</div>
`
})
export class MainComponent {
code: string = "";
constructor(private http: HttpClient, private router: Router){ }
goCalculate(){
this.http.post<IMetric>("https://localhost:5001/api/Helstead", this.code)
.subscribe(
(data) => {localStorage.setItem('key', JSON.stringify(data))},
);
this.router.navigate(['/metric']);
};
}
import {Component, Input} from '@angular/core';
import {Router} from "@angular/router";
@Component({
selector: 'about-app',
template: `
<div class="box">
<p class="resultOfTheMetric">Results of the Halstead metric</p>
<table class="tableOfOperators">
<caption class="nameOfTheTableOfOperators">Operators</caption>
<tbody>
<th>Value</th>
<th>Number of repetitions</th>
</tbody>
</table>
<table class="tableOfOperands">
<caption class="nameOfTheTableOfOperands">Operands</caption>
<tbody>
<th>Value</th>
<th>Number of repetitions</th>
</tbody>
</table>
<button (click)="goBack()" id="btn" class="shine-button">Go back</button>
</div>
<b>{{retrievedObject.numOfUniqueOperands}}</b>
`
})
export class MetricComponent {
retrievedObject = JSON.parse(<string>localStorage.getItem('key'));
constructor(private router: Router){}
goBack(){
this.router.navigate(['']);
}
}
Answer the question
In order to leave comments, you need to log in
Sending a request to the server is an asynchronous operation, and you jump to "/metric" as soon as you start sending the request, without waiting for it to complete. Therefore, at first, a transition is made to another route, and then the data is written to localStorage, therefore, they begin to be displayed after re-entering "/metric"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question