Angular 프로그램을 수동으로 시작하는 방법은 무엇입니까? Anglejs 프로그램을 수동으로 시작하는 방법에 대한 자세한 설명

寻∝梦
풀어 주다: 2018-09-07 16:52:25
원래의
1793명이 탐색했습니다.
이 글에서는 angularjs 프로그램을 수동으로 시작하는 방법을 주로 소개합니다. 여기서는 Anglejs 프로그램을 수동으로 시작하는 방법에 대해 자세히 설명합니다. 이제 Anglejs 프로그램을 수동으로 시작하는 방법을 살펴보겠습니다. Angular 프로그램을 시작하려면 main.ts 파일에 다음 코드를 작성해야 합니다.
platformBrowserDynamic().bootstrapModule(AppModule);
로그인 후 복사

이 코드 줄 platformBrowserDynamic()플랫폼, Angular의 공식 문서에서는 플랫폼을 다음과 같이 정의합니다. (역자 주: 명확한 이해를 위해 플랫폼의 정의는 다음과 같습니다. 번역되지 않음): main.ts 文件里写上如下代码:

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}
로그인 후 복사

这行代码 platformBrowserDynamic() 是为了构造一个 platform,Angular 官方文档对 platform 的定义是(译者注:为清晰理解,platform 定义不翻译):

the entry point for Angular on a web page. Each page has exactly one platform, and services (such as reflection) which are common to every Angular application running on the page are bound in its scope.

同时,Angular 也有 运行的程序实例(running application instance)的概念,你可以使用 ApplicationRef 标记(token)作为参数注入从而获取其实例。上文的 platform 定义也隐含了一个 platform 可以拥有多个 application 对象,而每一个 application 对象是通过 bootstrapModule 构造出来的,构造方法就像上文 main.ts 文件中使用的那样。所以,上文的 main.ts 文件中代码,首先构造了一个 platform 对象和一个 application 对象。

application 对象被正在构造时,Angular 会去检查模块 AppModulebootstrap 属性,该模块是用来启动程序的:

import { Component } from '@angular/core';

@Component({
  selector: 'a-comp',
  template: `<span>I am A component</span>`
})
export class AComponent {}

@Component({
  selector: 'b-comp',
  template: `<span>I am B component</span>`
})
export class BComponent {}
로그인 후 복사

bootstrap 属性通常包含用来启动程序的组件(译者注:即根组件),Angular 会在 DOM 中查询并匹配到该启动组件的选择器,然后实例化该启动组件。(想看更多就到PHP中文网AngularJS开发手册中学习)

Angular 启动过程隐含了你想要哪一个组件去启动程序,但是如果启动程序的组件是在运行时才被定义的该怎么办呢?当你获得该组件时,又该如何启动程序呢?事实上这是个非常简单的过程。

NgDoBootstrap

假设我们有 AB 两个组件,将编码决定运行时使用哪一个组件来启动程序,首先让我们定义这两个组件吧:

@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent],
  entryComponents: [AComponent, BComponent]
})
export class AppModule {}
로그인 후 복사

然后在 AppModule 中注册这两个组件:

<body>
  <h1 id="status">
     Loading AppComponent content here ...
  </h1>
</body>
로그인 후 복사

注意,这里因为我们得自定义启动程序,从而没有在 bootstrap 属性而是 entryComponents 属性中注册这两个组件,并且通过在 entryComponents 注册组件,Angular 编译器(译者注:Angular 提供了 @angular/compiler 包用来编译我们写的 angular 代码,同时还提供了 @angular/compiler-cli CLI 工具)会为这两个组件创建工厂类(译者注:Angular Compiler 在编译每一个组件时,会首先把该组件类转换为对应的组件工厂类,即 a.component.ts 被编译为 a.component.ngfactory.ts)。因为 Angular 会自动把在 bootstrap 属性中注册的组件自动加入入口组件列表,所以通常不需要把根组件注册到 entryComponents 属性中。(译者注:即在 bootstrap 属性中注册的组件不需要在 entryComponents 中重复注册)。

由于我们不知道 A 还是 B 组件会被使用,所以没法在 index.html 中指定选择器,所以 index.html 看起来只能这么写(译者注:我们不知道服务端返回的是 A 还是 B 组件信息):

export class AppModule {
  ngDoBootstrap(app) {  }
}
로그인 후 복사

如果此时运行程序会有如下错误:

The module AppModule was bootstrapped, but it does not declare “@NgModule.bootstrap” components nor a “ngDoBootstrap” method. Please define one of these

错误信息告诉我们, Angular 在向抱怨我们没有指定具体使用哪一个组件来启动程序,但是我们的确不能提前知道(译者注:我们不知道服务端何时返回什么)。等会儿我们得手动在 AppModule 类中添加 ngDoBootstrap 方法来启动程序:

// app - reference to the running application (ApplicationRef)
// name - name (selector) of the component to bootstrap
function bootstrapRootComponent(app, name) {
  // define the possible bootstrap components 
  // with their selectors (html host elements)
  // (译者注:定义从服务端可能返回的启动组件数组)
  const options = {
    'a-comp': AComponent,
    'b-comp': BComponent
  };
  // obtain reference to the DOM element that shows status
  // and change the status to `Loaded` 
  //(译者注:改变 id 为 #status 的内容)
  const statusElement = document.querySelector('#status');
  statusElement.textContent = 'Loaded';
  // create DOM element for the component being bootstrapped
  // and add it to the DOM
  // (译者注:创建一个 DOM 元素)
  const componentElement = document.createElement(name);
  document.body.appendChild(componentElement);
  // bootstrap the application with the selected component
  const component = options[name];
  app.bootstrap(component); // (译者注:使用 bootstrap() 方法启动组件)
}
로그인 후 복사
로그인 후 복사

Angular 会把 ApplicationRef 作为参数传给 ngDoBootstrap(译者注:参考 Angular 源码中这一行),等会准备启动程序时,使用 ApplicationRefbootstrap 方法初始化根组件。

让我们写一个自定义方法 bootstrapRootComponent

웹 페이지의 Angular 진입점입니다. 각 페이지에는 정확히 하나의 플랫폼이 있으며 페이지에서 실행되는 모든 Angular 애플리케이션에 공통되는 서비스(예: 리플렉션)가 해당 범위에 바인딩됩니다.🎜🎜At 동시에 Angular에는 애플리케이션 인스턴스 실행(애플리케이션 인스턴스 실행) 개념이 있으므로 ApplicationRef 토큰을 매개변수 주입으로 사용하여 해당 인스턴스를 얻을 수 있습니다. 위의 플랫폼 정의는 플랫폼이 여러 application 개체를 가질 수 있으며 각 application 개체는 다음과 같다는 것을 의미합니다. 위의 main.ts 파일에서 사용된 것과 동일한 구성 방법을 사용하여 bootstrapModule을 통해 생성됩니다. 따라서 위 main.ts 파일의 코드는 먼저 플랫폼 개체와 application 개체를 구성합니다. 🎜🎜 application 객체가 생성될 때 Angular는 프로그램을 시작하는 데 사용되는 AppModule 모듈의 bootstrap 속성을 ​​확인합니다. 🎜
function fetch(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('b-comp');
    }, 2000);
  });
}
로그인 후 복사
로그인 후 복사
🎜bootstrap 속성에는 일반적으로 프로그램을 시작하는 데 사용되는 구성 요소가 포함됩니다(번역자 참고 사항: 루트 구성 요소). Angular는 DOM에서 시작 구성 요소의 선택기를 쿼리하고 일치시킨 다음 시작을 인스턴스화합니다. 요소. (자세한 내용을 알고 싶다면 PHP 중국어 웹사이트 AngularJS 개발 매뉴얼🎜을 방문하여 알아보세요)🎜🎜Angular 시작 프로세스가 암시적입니다. 프로그램을 시작하려는 구성 요소는 무엇입니까? 하지만 프로그램을 시작하는 구성 요소가 런타임에 정의된 경우 어떻게 될까요? 구성 요소를 받으면 프로그램을 어떻게 시작합니까? 실제로는 매우 간단한 과정입니다. 🎜

NgDoBootstrap

🎜 AB라는 두 가지 구성 요소가 있다고 가정해 보겠습니다. 코딩에 따라 먼저 런타임에 프로그램을 시작하는 데 사용할 구성 요소가 결정됩니다. , 이 두 구성 요소를 정의해 보겠습니다.🎜
export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name)=>{ this.bootstrapRootComponent(app, name)});
  }
}
로그인 후 복사
로그인 후 복사
🎜그런 다음 AppModule에 이 두 구성 요소를 등록합니다.🎜
import {AComponentNgFactory, BComponentNgFactory} from './components.ngfactory.ts';
@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent]
})
export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name) => {this.bootstrapRootComponent(app, name);});
  }
  bootstrapRootComponent(app, name) {
    const options = {
      'a-comp': AComponentNgFactory,
      'b-comp': BComponentNgFactory
    };
    ...
로그인 후 복사
로그인 후 복사
🎜시작 프로그램을 사용자 정의해야 하기 때문에 부트스트랩이 없습니다. > code> 속성을 ​​사용하여 entryComponents 속성에 이 두 구성 요소를 등록하는 대신 entryComponents에 구성 요소를 등록함으로써 Angular 컴파일러(번역자 참고: Angular는 @angular/compiler 패키지는 우리가 작성한 각도 코드를 컴파일하는 데 사용되며 @angular/compiler-cli도 제공합니다. CLI 도구)는 이 두 구성 요소에 대한 팩토리 클래스를 생성합니다(번역자 참고 사항: 각 구성 요소를 컴파일할 때 Angular 컴파일러는 먼저 구성 요소 클래스를 해당 구성 요소 팩토리 클래스로 변환합니다. 즉, a.comComponent.ts는 a.comComponent로 컴파일됩니다. ngfactory.ts). Angular는 bootstrap 속성에 등록된 구성 요소를 항목 구성 요소 목록에 자동으로 추가하므로 일반적으로 entryComponents 속성에 루트 구성 요소를 등록할 필요가 없습니다. (역자 주: bootstrap 속성에 등록된 구성 요소는 entryComponents에 반복적으로 등록할 필요가 없습니다). 🎜🎜A 또는 B 구성 요소가 사용될지 모르기 때문에 index.html에서 선택기를 지정할 수 없습니다. 이므로 index.html이 작성하는 유일한 방법인 것 같습니다(역자 주: 서버가 A 또는 B를 반환하는지 여부는 알 수 없습니다). > 컴포넌트 정보): 🎜rrreee 🎜이때 프로그램을 실행하면 다음과 같은 오류가 발생합니다. 🎜🎜모듈 AppModule이 부트스트랩되었지만 “@NgModule.bootstrap” 컴포넌트나 “ngDoBootstrap” 메소드가 선언되지 않았습니다. . 다음 중 하나를 정의하십시오.🎜🎜오류 메시지는 Angular가 프로그램을 시작하는 데 사용할 구성 요소를 지정하지 않는다고 불평하지만 실제로는 미리 알 수 없음을 나타냅니다. 서버가 무엇이든 반환할 때). 나중에 프로그램을 시작하려면 ngDoBootstrap 메서드를 AppModule 클래스에 수동으로 추가해야 합니다. 🎜rrreee🎜Angular는 ApplicationRef를 매개변수로 전달합니다. ngDoBootstrap(번역자 참고 사항: Angular 소스 코드에서 이 줄을 참조하세요), 프로그램을 시작할 준비가 되면 ApplicationRef의 <code>bootstrap 메서드를 사용하세요. code> 루트 구성 요소를 초기화합니다. 🎜🎜루트 구성요소를 시작하기 위해 사용자 정의 메소드 bootstrapRootComponent를 작성해 보겠습니다. 🎜
// app - reference to the running application (ApplicationRef)
// name - name (selector) of the component to bootstrap
function bootstrapRootComponent(app, name) {
  // define the possible bootstrap components 
  // with their selectors (html host elements)
  // (译者注:定义从服务端可能返回的启动组件数组)
  const options = {
    'a-comp': AComponent,
    'b-comp': BComponent
  };
  // obtain reference to the DOM element that shows status
  // and change the status to `Loaded` 
  //(译者注:改变 id 为 #status 的内容)
  const statusElement = document.querySelector('#status');
  statusElement.textContent = 'Loaded';
  // create DOM element for the component being bootstrapped
  // and add it to the DOM
  // (译者注:创建一个 DOM 元素)
  const componentElement = document.createElement(name);
  document.body.appendChild(componentElement);
  // bootstrap the application with the selected component
  const component = options[name];
  app.bootstrap(component); // (译者注:使用 bootstrap() 方法启动组件)
}
로그인 후 복사
로그인 후 복사

传入该方法的参数是 ApplicationRef 和启动组件的名称,同时定义变量 options 来映射所有可能的启动组件,并以组件选择器作为 key,当我们从服务器中获取所需要信息后,再根据该信息查询是哪一个组件类。

先构建一个 fetch 方法来模拟 HTTP 请求,该请求会在 2 秒后返回 B 组件选择器即 b-comp 字符串:

function fetch(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('b-comp');
    }, 2000);
  });
}
로그인 후 복사
로그인 후 복사

现在我们拥有 bootstrap 方法来启动组件,在 AppModule 模块的 ngDoBootstrap 方法中使用该启动方法吧:

export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name)=>{ this.bootstrapRootComponent(app, name)});
  }
}
로그인 후 복사
로그인 후 복사

这里我做了个 stackblitz demo 来验证该解决方法。(译者注:译者把该作者 demo 中 angular 版本升级到最新版本 5.2.9,可以查看 angular-bootstrap-process,2 秒后会根据服务端返回信息自定义启动 application

在 AOT 中能工作么?

当然可以,你仅仅需要预编译所有组件,并使用组件的工厂类来启动程序:

import {AComponentNgFactory, BComponentNgFactory} from './components.ngfactory.ts';
@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent]
})
export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name) => {this.bootstrapRootComponent(app, name);});
  }
  bootstrapRootComponent(app, name) {
    const options = {
      'a-comp': AComponentNgFactory,
      'b-comp': BComponentNgFactory
    };
    ...
로그인 후 복사
로그인 후 복사

记住我们不需要在 entryComponents 属性中注册组件,因为我们已经有了组件的工厂类了,没必要再通过 Angular Compiler 去编译组件获得组件工厂类了。(译者注:components.ngfactory.ts 是由 Angular AOT Compiler 生成的,最新 Angular 版本 在 CLI 里隐藏了该信息,在内存里临时生成 xxx.factory.ts 文件,不像之前版本可以通过指令物理生成这中间临时文件,保存在硬盘里。)

好了,本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。

위 내용은 Angular 프로그램을 수동으로 시작하는 방법은 무엇입니까? Anglejs 프로그램을 수동으로 시작하는 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!