2017-02-21 1 views
3

그래서 Angular2에는 두 개의 구성 요소가 있습니다. 사용자가 component1의 버튼을 클릭하면 변수에 sharedservice의 데이터를 저장하는 메소드가 있습니다. 이 변수는 component2 ngOnInit()에서 액세스됩니다. 그러나 초기화 된 변수는 클릭 이벤트를 기다리지 않으므로 ngOnInit()에 정의되지 않음으로 초기화됩니다.angular2에서 사용자 클릭 이벤트를 기다리는 방법은 무엇입니까?

전체적으로 component2에서 angular2 component2 대기 이벤트를 어떻게 처리합니까?

JavaScript에서는 클릭 이벤트 리스너를 사용하거나 콜백 함수를 사용하여 쉽게이 작업을 수행 할 수 있지만 같은 생각을 구현하는 방법을 알지 못합니다.

아이디어를 공유해주세요.

modules.component.html

<tr *ngFor="let module of modules" #moduleObject> 
    <a class="test" (click)="module._clicked = !module._clicked"></a> 
    <ul class="dropdown-menu" role="menu" [ngStyle]="{'display': module._clicked ? 'block' : 'none'}" > 
    <li><a (click)="_showDialogue =! _showDialogue; _getModuleCode(module)"><img src="../../assets/img/pencil.svg" alt="" width="13px">Edit Module</a></li> 

    </ul> 
</tr> 

내가 그냥 modules.component.ts 여기에 모든 것을 날려 버릴 것 같은 modules.component.ts에서 불필요한 코드를 제거합니다 :

내가 지금까지 무엇을 가지고

import {SharedService} from "../shared/shared.service"; 
import {DepartmentsService} from "./departments.service"; 
import {ActivatedRoute, Params} from "@angular/router"; 
import {Module} from "../dashboard/Module"; 

@Component({ 
    selector: 'app-modules', 
    templateUrl: './modules.component.html', 
    providers: [DepartmentsService] 
}) 
export class ModulesComponent implements OnInit { 
    service; 

    modules: Module[]; 

    constructor(
    private activatedRoute: ActivatedRoute, 
    service : SharedService, 
    private departmentsService: DepartmentsService, 
    route: ActivatedRoute) { 
    route.params.subscribe(p => {this.department = p['dname']; }); 
    this.service = service; 
    } 

    _getModuleCode(moduleObject) { 
    this.departmentsService.moduleObject = moduleObject; 
    } 


    ngOnInit() { } 
} 

departments.service.ts

// assume necessary imports above 
@Injectable() 
export class DepartmentsService { 
    public _facultyName  :string; 
    public _departmentName :string; 
    public moduleObject:Module; 
    constructor() {} 
} 

은 그 때 나는이 구성 요소에서 moduleObject 변수를 호출 edit-forms.component.html

import {Module} from "./Module"; 
import {DepartmentsService} from "../components/departments.service"; 
//Change 
@Component({ 
    selector: 'enable-module-form', 
    templateUrl: './edit-forms.component.html', 
    providers:[ModuleService] 
}) 
export class EnableModFormComponent { 
    constructor( 
    private moduleService: ModuleService, 
    private departmentService: DepartmentsService 
) { } 

    ngOnInit(){ 
    console.log(this.departmentService.moduleObject); 
    } 

} 
+0

'관찰 가능'을 사용합니다. 좀 더 현실적인 답변을 드릴 수 있도록 시나리오 코드를 게시 할 수 있습니까? – acdcjunior

+0

확실한 것. @acdcjunior 위의 최신 편집을 확인하십시오 – DingDong

+0

행운이 있습니까? @acdcjunior – DingDong

답변

2

이 작동합니다!

DepartmentService :

_getModuleCode(moduleObject) { 
    this.departmentsService.moduleValueReceived(moduleObject); 
} 

자녀 생성자에서 값에 가입 :

private moduleSource = new Subject<any>(); 
moduleValue = this.moduleSource.asObservable(); 

moduleValueReceived(module) { 
    //emit value 
    this.moduleSource.next(module) 
} 

와 부모, 당신은 서비스의 값을 설정 한 값이있는 경우에

constructor( 
    private moduleService: ModuleService, 
    private departmentService: DepartmentsService 
) { 
    moduleService.moduleValue.subscribe(moduleObject => { 
     console.log(moduleObject); // here you have your value 
    }) 
    } 

Here in the official docs 내가 제공 한 것보다

희망이 도움이됩니다.

+0

다시 한 번 감사드립니다. 내가 너없이 무엇을 할 것인지 모르겠다. 정말 감사합니다. 그것은 효과가 있었지만. 그러나 어떤 이유에서, 'subscribe (i => i.console.log (i))'는 클릭 된 요소를 여러 번 인쇄합니다. 왜 그런가요? 클릭 한 요소를 한 번만 반환하려고합니다. – DingDong

+0

버튼 목록이 있기 때문에 버튼을 클릭하면 올바른 데이터를 얻을 수 있지만 'ul li'에있는 버튼 수에 따라 데이터가 반환됩니다 – DingDong

+0

여러 번 인쇄되면 잘됩니다. 변경이 일어날 때마다 자연스럽게 구독하기 때문에 변경 사항이 여러 번 발생한다고 제안합니다. 제공 한 코드에 버튼이 표시되지 않습니까? 조금 더 자세히 설명해 주시겠습니까? 다른 모든 코드는 무슨 일이 벌어지는 지에 관해 나에게 꽤 분명해 보였지만 실제로 버튼 몇 개가 있으면 html을 좀 더 보여줄 수 있습니까? 그래서 나는보기에서 진행되는 것에 대해 더 좋은 그림을 얻을 것입니다. – Alex

관련 문제