Cannot see the variable passed from one component to another unrelated component in Angular

Discussão em 'Angular' iniciado por craftdeer, Fevereiro 17, 2025.

  1. craftdeer

    craftdeer Guest

    I am trying to pass a string from one component(ProductComponent) to another unrelated component(SellerComponent) in Angular. The idea is to double click on a button on the ProductComponent and it brings us to a new screen(SellerComponent) but it should pass a string variable so that I can use it in my SellerComponent. I have seen tutorials where they are using services to pass data and I am trying to do the same.

    In myservice.service.ts

    @Injectable({
    providedIn: 'root'
    })
    export class myservice {
    private prodId= new Subject<string>();
    currentProdId = this.ProdId.asObservable();

    constructor() { }

    setProdId(prodId: string) {
    this.prodId.next(prodId);
    }
    }


    In ProductComponent

    constructor(private router: Router, private myservice: MyService) { }

    openSellerScreen(productId: string): void {
    this.myservice.setProdId(productId);
    this.router.navigate(['/product/sellerpage']);
    }


    In SellerComponent

    productId: string = '';
    subscription: Subscription;

    constructor(private myservice: Myservice) {
    this.subscription = this.myservice.currentProdId.subscribe(productId => {
    this.productId = productId;
    });



    In my seller component's html, I am trying to show the productId by doing

    <p>{{ productId }} </p>


    But all it is doing is showing blank. Is it not working because I am going to a different page by doing this.router.navigate? I cant understand why it wouldn't show.

    Continue reading...

Compartilhe esta Página