Home > Software engineering >  Angular: No duplicates in the code (transfer to service)
Angular: No duplicates in the code (transfer to service)

Time:07-15

I have a code that I use a lot when booting the app:(ngOnInit)

  this.route.queryParamMap.subscribe(
  params => {
    const id = params.get('id');
    if (id) {
      this.contactsService.GetContactByUserId(id)
        .subscribe(
          response => {
            this.contact = response;
          }
        )
    }
  }
)

I want to move this thing to service. And I will call the method from the service and not every component to add this part

What I was trying to do:

Service:

displayNameById(){
    this.route.queryParamMap.subscribe(
      params => {
        const id = params.get('id');
        if (id) {
          this.GetContactByUserId(id)
            .subscribe(
              response => {
                this.contact = response;
              }
            )
        }
      }
    )
  }

In the component I called this method:

ngOnInit(): void {
    this.contactsService.displayNameById();
  }   

Of course it does not work, does not display what I am asking for in html:

{{contact.displayName}}

CodePudding user response:

Angular v14 allows dependency injection via functions using inject(..) - there a good article on it and the example by Net Basel is pretty close to what you're doing

// uitlity function
import { inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export function getRouteParam(key: string) {
  return inject(ActivatedRoute).snapshot.params[key];
}

// component
@Component({
  selector: 'app-todo-page',
  templateUrl: './todo-page.component.html',
})
export class TodoPageComponent {
  id = getRouteParam('id');

  ngOnInit() {
    console.log(this.id)
  }
}

CodePudding user response:

In you service

constructor(private activeRoute: ActivatedRoute){}
displayNameById(){
  if(this.activeRoute.snapshot.params[key]){
   const id = this.activeRoute.snapshot.params[key];
   this.GetContactByUserId(id);
   return  id;
  }
}

and in your component you can call it in ngOnint:

ngOnInit(){
 let id = this.contactsService.displayNameById();
}
  • Related