角度2:使用服务广播事件 [英] angular 2: using a service to broadcast an event

查看:73
本文介绍了角度2:使用服务广播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个组件中单击按钮以将焦点放在另一个组件上的元素上. (坦率地说,我不明白为什么它必须如此复杂,但是我无法实现任何更简单的实际工作方式.)

I'm trying to get a button click in one component to put focus on an element on another component. (Frankly, I don't understand why this must be so complex, but I have not been able to implement any simpler way that actually works.)

我正在使用服务.除了发生点击的 之外,不需要传递任何数据.我不确定侦听组件是如何响应事件的.

I'm using a service. It doesn't need to pass any data except that the click occurred. I'm not sure how the listening component is meant to respond to the event.

app.component:

app.component:

跳至主要内容

import { Component } from '@angular/core';
import { SkipToContentService } from './services/skip-to-content.service';


export class AppComponent {
    constructor(
        private skipToContent: SkipToContentService
    ) {}
    }

    skipLink() {
        this.skipToContent.setClicked();
    }

}

登录组件:

<input type="text" name="username" />


import { Component, OnInit } from '@angular/core';
import { SkipToContentService } from '../../../services/skip-to-content.service';

export class BaseLoginComponent implements OnInit {

    constructor(
        private skipToContent: SkipToContentService
        ) {
    }

    ngOnInit() {
        this.skipToContent.skipClicked.subscribe(
            console.log("!")
            // should put focus() on input
        );

    }
}

跳至内容服务:

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class SkipToContentService {

    skipClicked: EventEmitter<boolean> = new EventEmitter();


    constructor() {
    }

    setClicked() {
        console.log('clicked');
        this.skipClicked.emit();
    };
}

对于登录如何听到" skipClicked事件,我有些困惑.

I'm a bit lost here as to how logon will "hear" the skipClicked event.

推荐答案

首先,使用BehaviorSubject代替EventEmitter.将skipCliekd的声明更改为以下内容:

First of all, use a BehaviorSubject instead of EventEmitter. Change the declaration of skipCliekd to the following:

skipClicked: BehaviorSubject<boolean> = new BehaviorSubject(false);

然后,您需要使用next()方法广播新值,如下所示:

Then, you need to broadcast the new value using next() method as following:

this.skipClicked.next (true);

此外,将您的订阅更改为:

Also, change your subscription to:

 this.skipToContent.skipClicked.subscribe( value => {
     if (value === true) {
         console.log("!"); 
         // should put focus() on input 
     }
 });

这篇关于角度2:使用服务广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆