kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

不同组件的*.component.ts 基本一样,但是用不了继承 #162

Closed ghost closed 6 years ago

ghost commented 8 years ago
import {Resource, ResourceParams,ResourceResult} from "ng2-resource-rest";
export class MainComponent {
    Results: ResourceResult;
    hasPrevious:boolean = true; //是否有上一页
    hasNext:boolean = true;//是否有下一页
    currentPage:number = 1;
    post:Object;

    constructor(public Res:any,public sidenav: any,
                public media: any) {
        this.init();
    }
    hasMedia(breakSize: string): boolean {
        return this.media.hasMedia(breakSize);
    }
    open(name: string) {
        this.sidenav.show(name);
    }
    close(name: string) {
        this.sidenav.hide(name);
    }

    init(){
        this.Results=this.Res.get()
            .$observable
            .subscribe(
                res => {
                    this.disabledPagination(res);
                    this.Results = res;
                },
                err => console.log('Err', err)
            );

    }
}

我的每个组件,基本都会用到上面的代码,我把他建立成了一个叫MainComponent 的独立组件,然后在其他组件里继承他,但是却老是出现各种错误

下面是我继承的核心代码,

方法1:

export class UserComponent extends MainComponent{
    constructor(){
        super();
        this.Res = UserRes;
        this.sidenav = sidenav01;
        this.media = media01;

    }
}

方法2:

export class UserComponent extends MainComponent{
    constructor(UserRes,sidenav01,media01){
        super(UserRes,sidenav01,media01); 

    }
}

2个方法都无法正常运行,请问是有什么地方我搞错了吗

kittencup commented 8 years ago

@Component 是写在 @Component 上的吗?

ghost commented 8 years ago

MainComponent 是在另外一个文件里,我import进来的 @kittencup

Shyam-Chen commented 8 years ago

為什麼你要擴展組件?

有 contentChild 阿!

ghost commented 8 years ago

@Shyam-Chen 因为我有好多个组件,有很多一样的方法,功能基本一样,所以就想继承,这样可以剩下很多代码

Shyam-Chen commented 8 years ago

是不是能放在服務,再注入到組件?

ghost commented 8 years ago

@Shyam-Chen 谢谢提醒

Shyam-Chen commented 7 years ago

已經在 Angular 可以用了

https://scotch.io/tutorials/component-inheritance-in-angular-2