Home > Software engineering >  Reuse component for 2 different screens
Reuse component for 2 different screens

Time:11-13

I have 2 different screens whereby the ui of both screens are the same. I have integrated with the api for one of the screen. However, as both screens reuse the same component, how can a component integrate with 2 different apis?

CodePudding user response:

Your question is too vague so it will generate a lot of answers that probably have nothing to do with your question.

My interpretation of your question is that you have 2 pages that look the same but their data should come from 2 different API’s and you wonder how to reuse the same component for both screens.

I would split the component in a pure presentational component that only receives data via @Input() and renders it. This is the part you can reuse. Then create 2 separate container-components, (one for each page) which retrieves the API data in whatever way it needs to and then feeds that data to your presentational component. This approach follows SRP (Single Responsibility Principle)

CodePudding user response:

you add your backend url in environment.ts file

For example : in environment.ts :

export const environment = {
  production: false,
  baseurl:"http://localhost:8040"    <-- That line of code
};

CodePudding user response:

To solve this problem, there can be multiple ways to solve it. I had also the same problem statement.

So here few things which I did(which may be not feasible to you)

  • Added one extra query params key in the URL for my 2nd UI (same UI)
  • Now in my top most parent component of that feature module, I captured that query params and passed it to the required child components.
  • In service created the 2 URLS for the same UI

For example:

getDataForFirstUIUrl = 'http:/www.firsturl.com';
getDataForSecondUIUrl = 'http:/www.secondurl.com'

getDataForBothUI(myQueryParamsFlag: boolean): Observable<any> {
  return this.http.get(myQueryParamsFlag ? this.getDataForFirstUIUrl : this.getDataForSecondUIUrl)
}
  • Now in your component you should try like this:

    @Input() myQueryParamsFlag: boolean;
      getDataForMyUI() {
        this.myService.getDataForBothUI(myQueryParamsFlag).subscribe((data) => {
          // do whatever you want to do
        })
      }
    
  • Related