2017-11-30 5 views
0

두 구성 요소가 있습니다.다른 구성 요소에서 한 구성 요소의 기능을 호출하는 적절한 방법

요소 1은 컴포넌트 2가

@Component({ 
selector: 'app-sites', 
templateUrl: './sites.component.html', 
styleUrls: ['./sites.component.scss'] 
}) 
export class SitesComponent implements OnInit { 
list: Site[]; 

constructor(private ctxMenu: ContextualMenuSyncService) { 
    this.ctxMenu.sync("sites"); 
    this.ctxMenu.add = this.add; 
} 

ngOnInit() { } 

add() {  
    this.router.navigateByUrl("/newsite"); 
} 
} 

호출되는 기능을 갖는 구성 요소가 마지막가된다

@Component({ 
selector: 'app-contextualmenu', 
templateUrl: './contextualmenu.component.html', 
styleUrls: ['./contextualmenu.component.scss'] 
}) 
export class ContextualMenuComponent implements OnInit { 
context: string;  

constructor(private ctxMenu: ContextualMenuSyncService,) { 
    ctxMenu.context$.subscribe(v => { this.context = v; }); 
} 

ngOnInit() {} 

add() { 
    this.ctxMenu.add(); 
} 
} 

함수를 호출하는 작은 FAB 메뉴 아이콘 일 ContextualMenuSyncService 두 구성 요소 사이의 도관 역할을합니다.

@Injectable() export class ContextualMenuSyncService { private context = new Subject<string>(); context$ = this.context.asObservable(); add: Function; constructor() { } sync(value: string) { this.context.next(value); } } 

그래서 간단히 말해서 나는 add() 구성 요소 2
add()에서 구성 요소 I 위와 같이 공유 서비스가 적절한이 주제에 읽은 내용에 따르면 1

의 전화를 시도하고있다 방법을 사용하여 구성 요소 간 통신을 수행 할 수 있습니다.

그러나 내 문제는 내가 add()이라고 부를 때 ContextualMenuSyncService 컨텍스트에서 실행 중입니다. this을 의미하는 것은 ContextualMenuSyncService 및하지 당신이 구성 요소의 멤버 함수를 호출하려면 어떻게 SitesComponent (구성 요소 2) 등 내가 SitesComponent (구성 요소 2) 멤버로 주입, 정보에 액세스 할 수 없음을 의미,

첫 번째 구성 요소의 맥락에서 다른 구성 요소로부터?

답변

0

add 값을 명시 적으로 바인딩하여 구성 요소 2의 this 값을 가져와야합니다. 이이 일을 여러 가지 방법으로, 그러나 가장 쉽고 가장 인기가 추가 할 때 지금과 같은 화살표 기능을 사용하는 것입니다 중 addctxMenu에 : 또는

this.ctxMenu.add =() => this.add(); // maintains Component2's this 

, 당신과 같이 bind을 사용할 수

this.ctxMenu.add = this.add.bind(this); // maintains Component2's this 
+0

나는 그것에 대한 후속 조치를 취할 수 있습니까? 함수에 매개 변수가 있으면 어떻게 될까요? 'this.simpleSearch.searchFunction =() => this.search();'this.search()는 실제로'search (term)'로 정의되기 때문에 서명이 일치하지 않습니다. 하지만 'this.simpleSearch.searchFunction =() => this.search (term);'를 수행하면'term '이 무엇인지 알지 못한다고 불평합니다. – americanslon

0

좀 더 이런 식으로 할 거라고 : 기능이 실행되는 경우

구성 요소 :

@Component({ 
selector: 'app-sites', 
templateUrl: './sites.component.html', 
styleUrls: ['./sites.component.scss'] 
}) 
export class SitesComponent implements OnInit, OnDestroy { 
list: Site[]; 
private addSub; 

constructor(private ctxMenu: ContextualMenuSyncService) { 
    this.ctxMenu.sync("sites"); 
    this.addSub = this.ctxMenu.add$.subscribe(() => this.add()); 
} 

ngOnInit() { } 

ngOnDestroy() { this.addSub.unsubscribe(); } // always unsubscribe 

add() {  
    this.router.navigateByUrl("/newsite"); 
} 
} 

서비스 :

@Injectable() 
export class ContextualMenuSyncService { 
private context = new Subject<string>(); 
context$ = this.context.asObservable(); 

private addSource: Subject<any> = new Subject(); 
add$: Observable<any> = this.addSource.asObservable(); 
add() { 
    this.addSource.next(); 
} 

constructor() { } 

sync(value: string) { 
    this.context.next(value); 
} 
} 

서비스를 호출하는 기능이 괜찮습니다.

관련 문제