多次调用Observable.Subscribe是否会创建多个订阅?

时间:2018-11-09 15:40:29

标签: typescript observable subscription

您好,我在Component中使用的是Service方法,该方法又返回了observable。我想知道的是,如果我在组件中多次调用Subscribe会创建多个订阅,从而导致应用程序中断吗?

服务方法

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;

组件

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(); 

        }

    }

如果在我的HTML中,我将getUsers方法附加到click事件中……我会产生新的订阅吗?

1 个答案:

答案 0 :(得分:1)

当UserService.getClients http调用发出事件或错误时,解析getUsers()中的订阅。请不要惊慌并继续。