2016-08-21 11 views
0

두 개의 다른 형식 클래스를 사용하는 경우를 제외하고 같은 방법을 사용하는 두 개의 페이지 구성 요소가 있습니다. 이 두 구성 요소를 서비스 및 사용자라고합니다. 두 구성 요소 모두 표시되는 클래스 속성 정보를 제외하고는 매우 유사한 템플릿을 사용합니다. 두 컨트롤러 모두에서 메서드를 반복하는 것은 비효율적 인 것처럼 보입니다. 컨트롤러를 결합/공유하는 방법이 있습니까?Angular2 - 공유 구성 요소 컨트롤러

Services.ts

import { Component } from '@angular/core'; 
import { CORE_DIRECTIVES } from '@angular/common'; 
const template = require('./service.component.html'); 
const style = require('./service.component.css'); 

interface Service { 
    id: number; 
    name: string; 
    summary: string; 
    path: string; 
}; 

@Component({ 
    selector: 'admin-services', 
    directives: [ CORE_DIRECTIVES], 
    template: template, 
    styles: [ style ] 
}) 

export class ServiceComponent { 
    services = Services; 
    selectedService:Service ; 
    constructor() { 
    } 

    onselect(service:Service){ 
    this.selectedService = service ; 
    } 
    onEdit(service:Service){ 
    console.log("Edit: "+service); 
    } 
    onDelete(service:Service){ 
     console.log("Delete: "+service); 
    } 
    onView(service:Service){ 
    console.log("View: "+service); 
    } 
    onAdd(){ 
    this.selectedService = <Service>{}; 
    } 
} 

User.ts는

import { Component } from '@angular/core'; 
import { CORE_DIRECTIVES } from '@angular/common'; 
const template = require('./users.component.html'); 
const style = require('./users.component.css'); 

interface User { 
    id: number; 
    image: string; 
    name: string; 
    email: string; 
    role: string; 
}; 

@Component({ 
    selector: 'admin-users', 
    directives: [ CORE_DIRECTIVES], 
    template: template, 
    styles: [ style ] 
}) 

export class UsersComponent { 
    users = Users; 
    selectedUser:User ; 
    constructor() { 
    } 

    onselect(user:User){ 
    this.selectedUser = user ; 
    } 
    onEdit(user:User){ 
    console.log("Edit: "+user); 
    } 
    onDelete(user:User){ 
     console.log("Delete: "+user); 
    } 
    onView(user:User){ 
    console.log("View: "+user); 
    } 
    onAdd(){ 
    this.selectedUser = <User>{}; 
    } 
} 

답변

2

그래,이 코너의 구성 요소 중심의 디자인 타이프 친의 클래스 기반의 디자인은 정말 빛나는 곳이다 :

@Component({ 
    selector: 'admin-users', 
    directives: [ CORE_DIRECTIVES], 
    template: template, 
    styles: [ style ] 
}) 
export class UsersComponent extends ServicesComponent { 
    constructor(){ 
     super(); 
    } 

    //override whatever methods/fields in the parent class you need to (and only those) 


} 
+0

그럼 servic에서 메소드를 만든 다음 사용자 컨트롤러에서 다시 메소드를 만들어야합니다. – John

+0

위의 예에서,'UsersComponent' 컨트롤러 클래스는 그것이 확장 한'ServicesComponent' 클래스의 모든 메소드를 상속받습니다, 그들은 다시 구현할 필요가 없습니다. – drewmoore

+0

이 오류가 발생합니다. 파생 클래스의 생성자에는 'super'호출이 포함되어야합니다. – John

0

난 당신이 방법의 한 세트와 서비스를 만들고 객체를 전달할 수 있다고 생각합니다. 그런 다음 원하는 클래스에 객체를 캐스팅하고 메서드에 사용합니다.

은 위 가지고, 당신은 단순히 클래스를 확장하고 여기에 다른 구성 요소의 메타 데이터를 첨부 할 수 ServicesComponent을 정의한 후 :

+0

그런 다음 서비스에서 메소드를 만든 다음 내 컨트롤러에서 다시 만들어야합니다. – John

관련 문제