Search code examples
angularangular-services

Angular CLI Services stored String variable always return to default value


I'm new to angular CLI. this happened when I tried to pass a string value to services and later tried to retrieve it in another component

select.ts

public gotofriends(fname:string, fpic:string){    
    const service = new FbdetailsService();
    service.selectedfrienddetails(fname, fpic);
    this.router.navigate(['calculate']);
}

select.html

<button (click)="gotofriends(user.name,user.picture.data.url)" class="btn btn-lg btn-primary mx-1">Select &nbsp;</button>

fbdetails service

export class FbdetailsService {
    fbname;
    fbpic;
    public selectedfrienddetails(name: string, profilephoto: string) {
        this.fbname = name;
        this.fbpic = profilephoto;
        console.log("selected friend details", this.fbname, this.fbpic)
    }


    public returnfrienddetails() {
        console.log(this.fbname, this.fbpic)
    }
}

calculate componet.ts

public printname(){
    const service = new FbdetailsService();
    service.returnfrienddetails()
}

calculate HTML

<button (click)="printname()" class="btn btn-lg btn-primary mx-1">Calculate</button>

when I call selectedfrienddetails() in selectcomponet.ts it succefully printing string to console but when I tried to call returnfrienddetails() in calculatecomponent.ts it doesn't print any value .

then I tried adding two buttons to selectcomponent.ts
first one pass selectedfrienddetails() and successfully print variable then second one call returnfrienddetails() but as in first case returnfrienddetails() didn't print anything.


Solution

  • In Angular, services are singletons. That means there is only one instance of them.

    What you, is creating a second :

    const service = new FbdetailsService();
    

    You should not. Instead, you should inject your service into your components. For that, decorate your service as injectable, and inject it into your component constructors.