2

I am trying to figure out what is the proper way of implementing dynamic links in angular application. It could be that I'm reinventing the wheel.

Lets say that in some component view I want to add link to my application page.

Static way to do it would be:

<a routerLink="/target-page/">Target Page</a>

Problem: if in my routes I change the name 'target-page' to 'target-page-2' I have to edit this link in every page I use it.

I was thinking of creating a new js file to collect links and then always generate links from that file.

File: 'links.ts' (which I would include everywhere)

links: Array<{ name: string; path: string }> = [
   { name: 'home', path: '/homepage/' },
   { name: 'register', path: '/registration-page/' }
];

function getLink(name: string){
   return links.filter(e=>e.name===name).pop().path;
}

File: 'someview.html'

<a routerLink="{{ getLink('register') }}">Register</a>

However,the problem is that a view does not have access to function "getLink()", I have to re-create it in every component.ts. Is there a way to include this function automatically in every component.ts or access it globally in a view?

1
  • NOTE: NOT put "function" to define a function. BAD: function myfunction(){..}, GOOD, myfunction(){...} Commented Jan 24, 2019 at 7:47

1 Answer 1

2

Create service ng g service common.

Then set function in service file.

getlink(name: string){
    return links.filter(e=>e.name===name).pop().path;
}

Add service in providers. `// Not required, It depends your angular version.

then , import service in component.

add service in constructor

constructor(private commonService:CommonService){
}

//Now call function where you want 
let link = this.commonService.getLink('login');
console.log("Link",link);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.