首页 > 解决方案 > Angular:扩展具有多个孩子的服务

问题描述

从多个子项扩展服务会创建服务的新实例。我希望能够扩展一项服务,如果一个孩子的数据发生变化,另一个孩子也应该可以使用它。

我尝试过创建服务。我创建了两个模块,它们都在扩展服务。

@Injectable({
    providedIn: 'root'
})
export class BaseService {
    //Api stuff going on here
    constructor(){

    }
}

@Injectable({
    providedIn: 'root'
})
export class AuthService extends BaseService {
    //Login stuff going on there
    constructor(){
        super()
    }
}

export class LoginPage extends AuthService {
    //Handles login
    constructor(){
        super()
    }
}

@Injectable({
    providedIn: 'root'
})
export class UserService extends AuthService {
    //User stuff going on here
    constructor(){
        super()
    }
}

export class ProfilePage extends UserService {
    //Handles user stuff
    constructor(){
        super()
    }
}

//So LoginPage and UserService are both extending AuthService. For example
//setting a token from LoginPage ->AuthService should make the token available //in the UserService. But how it is now is that it creates multiple instances //of AuthService. Is this even possible to accomplish?

我想知道这是否可能。我知道注入服务的基本方法,但这更酷更实用。

标签: angulartypescriptoopextends

解决方案


推荐阅读