Home > OS >  How to save component data in an Angular service?
How to save component data in an Angular service?

Time:12-14

I currently have a dice game component on Angular and the dice roll results are saved in a TypeScript array then displayed in HTML. Now I'm told I need to save the results in a service so that if I travel to another page and come back, the same results are still displayed. I've searched for ways to do it but I can only find ways to save data from a component to another, not in the same one. If anyone knows how I can achieve this, please help! Here is my code. Regards,

diceResults: number[] = [];

  rollTheDice() {
    for (let i in this.diceGame) {
      for (let a = 0; a < this.diceGame[i].numberOfDices; a  ) {
        this.diceResults.push((Math.random() * (this.diceGame[i].numberOfFaces - 1)   1))
      }
    }
  }

 <button *ngFor="let dice of diceResults" >{{ dice | number: '1.0-0' }}</button>

CodePudding user response:

You can save data in a service as follows:

export YourServiceName {
private diceResults: number[] = [];

}

Create a getter and setter in that service:

setDice(diceValues : number[]) {
this.diceResults = diceValues
}
getDice():void {
return this.diceResults
}

Then you can call these in components.

CodePudding user response:

Building on @CallMeAnytimeOkay answer.

To declare a service, you would need to specify it as a provider in a module. Let says in your app.module.ts for simplicity sake:

@NgModule({
  declarations: [AppComponent],
  imports: [...],
  providers: [YourServiceName],
})
export class AppModule {}

Then create the service file yourServiceName.service.ts:

@Injectable({providedIn: 'root'}) //Note that you will need to declare it as `@Injectable`. 
export class YourServiceName {
  private _diceResults: number[] | null = null;
  public set diceResults(result: number[] | null) {
    this._diceResults = result;
    if(result != null) localStorage.setItem("diceResults", JSON.stringify(result));
    else localStorage.removeItem("diceResults");
  }

  public get diceResults(): number[] | null {
    if(this._diceResults == null) {
      const data = localStorage.getItem("diceResults");
      return JSON.parse(data)
    } else return this._diceResults;
  }
}

Then declare the variable, getter, and setter as @CallMeAnytimeOkay mentioned.

To use the variable, you will need to inject the service into your component.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  diceResults: number[] = [];

  constructor(public yourService: YourServiceName) { }

  rollTheDice() {
    for (let i in this.diceGame) {
      for (let a = 0; a < this.diceGame[i].numberOfDices; a  ) {
        this.diceResults.push((Math.random() * (this.diceGame[i].numberOfFaces - 1)   1))
      }
    }
    this.yourService.diceResults = this.diceResults;
  }
}

CodePudding user response:

Create a new Service that should oversee the data saving and implement logic in that service. It should have a fitting object to store the values. It should have functions to manipulate that object, preferably with a parameter which holds the value to be persisted.

Then inject your service in your component where the dice results is created/calculated and then call the manipulation method from your service with the result as the parameter. For example when you press the button.

Further reading: Angular Data Tutorial

  • Related