Gopi krishna
Gopi krishna

Reputation: 21

How to clear values that are stored in service in angular 6 application?

Thanks in advance. I am beginner to angular 6.I need help regarding angular 6 services. With in my application, we are using angular 6 services for storing and fetching data. At some instance, I need to clear the service. Is there any angular inbuilt method to clear the service or I need to do it manually y assigning it to default values.

Upvotes: 1

Views: 8299

Answers (2)

Ganesh
Ganesh

Reputation: 6016

We don't have any specific methods to clear angular service variables, but we can do this just with assigning empty objects to them.

  1. it's an object then -- this.service.objectProperty = undefined;

  2. Array -- this.service.arrayProperty = [];

  3. if it's Map -- this.service.mapProperty.clear();

for more info about this, refer here

Upvotes: 1

Hypenate
Hypenate

Reputation: 2064

On component A I use Angulars DI system to automatically inject the same ApiService on all the components.

On component B however I set my own version of the ApiService.

import { Component } from '@angular/core'; 
import { ApiService } from './api.service'; 

// ./a.component.ts
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AComponent {     
  public constructor(api:ApiService){ 
  } 
} 

 // ./b.component.ts
 @Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
  providers: [APIService], <------ use a "new" APIService
 })

 export class BComponent { 

  public constructor(api:ApiService){        
  }  
} 

But if you would just want to clear a value, you could use this in your component: this.api.someProperty = undefined.
Note that this will clear the property for all components using ApiService that use the Angular DI system.

Upvotes: 0

Related Questions