【问题标题】:Import classes and external libaries in Angular2?在 Angular 2 中导入类和外部库?
【发布时间】:2017-10-26 10:31:42
【问题描述】:

我正在从另一个类导入 ts 中的外部类。

import {client} from '../../'

在另一个类中使用它之前,我是否需要创建一个新的 var 实例? (例如let cli = new client()})我看到了一些教程,其中一些大麦谈论这个。他们只是直接导入并使用它。

希望你能解释一下。

谢谢

【问题讨论】:

    标签: angular typescript import


    【解决方案1】:

    这取决于您要导入的内容..

    如果是CLASS ... 那么:YES .. 例如:

    export class User{
    
    public name:string;
    public surname:string;
    }
    

    然后在你的其他 ts 文件中:

    import { User } from '../../User';
    
    let user= new User();
    user.name= 'Fred';
    user.surname = 'Scamuzzi';
    

    如果您要导入例如 INTERFACE .. 则否:

    例如

    import {  OnInit } from '@angular/core';
      import { User } from '../../User';
    
    export class AppComponent implements OnInit { // --> it force you to implement the method declared in OnInit interface
    
    
    ngOnInit(): void { // implemented
    
            let currentUser = new User();
        }
    
    }
    

    当你在 NgModule 中导入一个组件来声明它时,同样的例子......你只需这样做:

    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    import { AppComponent } from './app.component';
    import {AuthService} from './shared/services/AuthService.service';
    
    @NgModule({
        imports: [
            BrowserModule,
    
            HttpClientModule
        ],
        declarations: [
            AppComponent
    
        ],
        providers: [
    
            AuthService
    
        ],
    
        bootstrap: [AppComponent]
    })
    export class AppModule {
    
    }
    

    希望对你有所帮助....

    【讨论】:

    • 好的,如果我导入一个命名空间,是一样的吗?仍然需要创建该命名空间的新实例吗?谢谢
    猜你喜欢
    • 2017-06-21
    • 2017-04-21
    • 2023-03-04
    • 2017-02-27
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多