Search code examples
typescriptobservablesubscription

Does calling Observable.Subscribe multiple times create multiple subscriptions?


Hello in my Component i am using a Service method which in turn returns an observable. What i want to know is if i call Subscribe multiple times in the component will this create multiple subscriptions and thus in time break the application?

Service method

getClients():Observable<User[]>{

      let route=UserService.baseUrl+"/users";
      var data= this.http.get(route)
        .map(resp=>resp)
        .catch(error=>{console.log(error);return Observable.throw(JSON.stringify(error));}) as Observable<User[]>;
     return data;

Component

export class IndexComponent {

        private canPress:boolean;

        public enableButtons: boolean;

        public users: Array<User>;
        constructor(private userservice:UserService,private router:Router) {

        }
        private getUsers(){
            console.log("Entered init");

            this.userservice.getClients().subscribe(data=>{
                this.users=data;
                this.canPress=this.users.length>0;
            },error=>{
                console.log("From Index: Could not obtain users");
                this.users=UserService.users;
                console.log(this.users);
            });

        }
        ngOnInit(): void {
            this.getUsers(); 

        }

    }

If in my HTML i attach the getUsers method to a click event ...will i spawn new subscriptions ?


Solution

  • Subscription inside getUsers() is resolved when UserService.getClients http call emits event or error. Please do not panic and carry on.