JmanxC
JmanxC

Reputation: 387

How to use the same instance of an object in 2 different components-Angular

I have a object I made in typescript that simulates a bank with getBalance(),setBalance(),deposit() and withdraw(). In one component I set the balance to display to the user and then on this screen user can select withdraw or deposit which then links to a withdraw or deposit component. How would I go about passing this same Bank Object back and forth between home page<-->withdraw and homepage<-->deposit as on all of these pages I want it to display the current balance(using bank.getBalance()). Not sure this matters but the homepage and withdraw/deposit components are all in separate modules. Any working example would be appreciated!

Upvotes: 1

Views: 852

Answers (1)

AyseAsude
AyseAsude

Reputation: 581

By using services, you can share data between components. Angular documentation for services: https://angular.io/tutorial/toh-pt4#injectable-services .

Create a service at the top level by:

ng generate service bank

After that, inject this service to each component where you need to share data by adding it to the constructors, for example:

constructor( private bankService: BankService ){}

You can declare a Bank Object in service, then provide get and set methods:

get getBank(){
   return this.bankObject;
}

setBank(bankObj: Bank){
   this.bankObject = bankObj;
}

You can set and get the Bank Object by calling getBank() and setBank() from your components. However, this is just a basic (abstract) example for a service. In real world, you may want to wait for your backend, or getting updated values without calling methods. In those cases, Observables and Subscriptions come into place. I suggest you to check Angular documents.

EDIT after comment: If data means authentication in your case, you can check https://firebase.google.com/docs/auth/web/auth-state-persistence .

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION).then(() => {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
.catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

firebase.auth.Auth.Persistence.SESSION will keep user's authentication until the window closes or firebase.auth.Auth.Persistence.LOCAL will keep user's authentication until he logouts.

However, if you've meant to not losing components data such as forms, objects; you need a custom route reuse strategy. Documentation : https://angular.io/api/router/RouteReuseStrategy

Upvotes: 1

Related Questions