0

I need to pass current userId to routerlink in borrow_list component

The way i declare userId in borrow_list component

userId: number;
constructor(private authService: AuthService, private bookService: BookService,
     private route: ActivatedRoute, private alertify: AlertifyService) { }



ngOnInit() {
    this.userId = this.authService.decodedToken.nameid;
    this.route.data.subscribe(data => {
      this.books = data['books'].result;
      this.pagination = data['books'].pagination;
    });
    this.borrowParam = 'loan';
    console.log(this.userId); // this one return 26
  }

Then i tried to pass userId to another component using routerlink

<div class="row">
  <div *ngFor="let b of books" class="col-sm-6 col-md-4 col-lg-4 col-xl-2">
    <app-book-card [book]="b"></app-book-card>
    <button class="btn btn-primary" [routerLink]=" 
     ['/browse/book/',this.userId,'/content/', b.id]" style="width: 75px">Read 
    </button>
  </div>
</div>

But it seem not working, no error but it direct me back to Home page

When i try to hard code the link and it work as intended i.e

[routerLink]="['/browse/book/26/content/', b.id]"

My routes.ts

{path: 'browse/book/:id/content/:bookId', component: Book_contentComponent, resolve: {book: BookContentResolver}}

I think i did it wrong somewhere?

1
  • Just try using: <button class="btn btn-primary" [routerLink]=" ['/browse/book/', userId, '/content/', b.id]" style="width: 75px">Read </button>. See there is no this with userId, give a try. Commented Apr 29, 2019 at 11:58

2 Answers 2

2

please try this:

<button class="btn btn-primary" [routerLink]=" ['browse', 'book', userId, 'content', 
b.id]" style="width: 75px">Read </button>

Every path segment is an element in the array.

Sign up to request clarification or add additional context in comments.

Comments

0

When in template, variables are automatically taken from the underlying component. So you don't need to put this to access member variables.

In your code, you just need userId instead of this.userId, giving:

<button class="btn btn-primary" [routerLink]=" 
 ['/browse/book/', userId,'/content/', b.id]" style="width: 75px">Read 
</button>

Note: not a good practice to put style inline in your HTML.

2 Comments

Tried still have the same problem
are you sure this.userId actually has the right value? Try console.log(this.userId); at the end of ngOnInit.

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.