我应该如何在Angular 4中的组件的HTML模板中使用Service中的BehaviorSubject类?

Pat*_* M. 2 service typescript firebase-authentication angular

我有一个用于身份验证的服务,它暴露了BehaviorSubject类的用户.我想在组件中使用该服务来允许登录/注销并显示用户属性....那里没什么新东西.

我知道我可以订阅组件中的用户对象并将结果分配给本地对象,而本地对象又将在视图中使用.但我有兴趣知道如何使用它而无需订阅打字稿,但直接在html中,感谢异步管道,我想.

这些是我将使用的伪类:

Auth服务

export class User {
    id: string;
    username: string;
    gender: string;

    constructor( some params...) {
        // set all the attributes...
    }
}


@Injectable()
export class AuthService {

    private _currentUser: BehaviorSubject<User> = new BehaviorSubject(null);
    get currentUser() {
        // do some logic here if needed
        return this._currentUser;
    }

    constructor() {}

    login(email, password)  {
        DoSomeHttpRequestToLogin()
        .then( userParams => {
            const user = new User(userParams);
            this._currentUser.next(user);
            })
        .catch(error => {});
    }   
}
Run Code Online (Sandbox Code Playgroud)

组件

@Component({
    selector: 'app-main',
    templateUrl: './main.component.html'
})
export class MainComponent implements OnInit {

    notWhatIWantToUse_User: User;
    currentUser$: ????

    constructor( private _authService: AuthService ) {

        // With subscription, which I'd like to avoid
        this.authService.currentUser.subscribe( user => {
            this.notWhatIWantToUse_User = user;
        }

        // Without subscription, my goal
        this.currentUser = this.authService.currentUser;
    }   

    ngOnInit() {
        this.authService.login();
    }
}
Run Code Online (Sandbox Code Playgroud)

main.component.html

<h1> First Method: Hello {{ notWhatIWantToUse_User?.username }} </h1>  <!-- this works -->
<h1> Second Method: Hello {{ ... some code with currentUser$ to show username, or id or gender... }} </h1>
Run Code Online (Sandbox Code Playgroud)
  • 如何使第二种方法有效?
  • 在这种情况下,最佳做法是什么?
  • 使用'share()'来避免重复隐式订阅怎么样?

谢谢您的帮助

Gün*_*uer 9

您可以使用async管道进行订阅

First Method: Hello {{ (authService.currentUser | async)?.username }}
Run Code Online (Sandbox Code Playgroud)

如果您使用这个特别好,ChangeDetectionStrategy.OnPush因为异步管道会在发出新值时自动通知更改检测以运行.