0

I hanve an abstract DataService which will probably have several implementations. I want to have an implementation that uses LocalStorage as backend, mainly for testing, and probably a Google and Facebook backend to store my app data:

@Injectable({
  providedIn: 'root'
})
abstract class DataService {
  abstract get(token: string): Observable<any>
  abstract set(token:string, data: any): void
}

@Injectable({
  providedIn: 'root'
})
export class LocalDataService implements DataService {

  constructor() {}

  get(token: string): Observable<string> {
    return of(localStorage.getItem(token));
  }

  set(token: string, data: string): void {
    localStorage.setItem(token, data);
  }
}

@Injectable({
  providedIn: 'root'
})
export class GDriveDataService implements DataService {...}

@Injectable({
  providedIn: 'root'
})
export class FacebookDataService implements DataService {...}

My problem is that I can only know which implementation to use after the user logs in with either Google or Facebook account.

Is it possible to switch the provided impmlementation of the Service after tha app has been bootstrapped? Do I need to take a different approach?

Hodossy Szabolcs
  • 1,598
  • 3
  • 18
  • 34
  • This might help: https://stackoverflow.com/questions/52110168/angular-6-is-it-possible-to-inject-service-by-condition https://stackoverflow.com/questions/43450259/angular-2-conditionally-inject-service-in-component/43450317 – Jojofoulk May 23 '19 at 07:14
  • You can do it in a module, which means you can control *before build* which implementation to use, but I'm not sure you can do it at runtime ... –  May 23 '19 at 07:15
  • 1
    @Jojofoulk Thanks, but I don't want my components to even know about the implementation, they would just use `DataService`, or whatever is injected with that token. – Hodossy Szabolcs May 23 '19 at 07:23

0 Answers0