search
HomeWeb Front-endJS TutorialDetailed explanation of the architecture usage of Angular 4.0

Detailed explanation of the architecture usage of Angular 4.0

Apr 18, 2018 am 09:35 AM
angularArchitectureDetailed explanation

This time I will bring you a detailed explanation of the use of the Angular 4.0 architecture. What are the precautions when using the Angular 4.0 architecture. The following is a practical case, let's take a look.

Preface

Some time ago, Google released version 4.0 of the popular Angular JavaScript framework. This version is committed to reducing the size of generated code and maintaining a simplified release plan for the framework.

It’s been a long time since I wrote something more conceptual like this, but I feel that without forming a knowledge structure, learning efficiency will be greatly reduced. Here I will share with you the knowledge I understand, and some of the content is quoted from official documents. Let’s go to the topic

Angular Architecture Overview

This architecture diagram shows the 8 main building blocks in an Angular application:

Next, I will explain it in order and with pictures.

1. Module

New projects created by Angular or ionic will have a root module, and the default name is AppModule. If you use Modular to create an application, include AppModule, each will have a @NgModule decorator class (although it is very similar to java annotation in , but its official name is decorator). If our new page does not use lazy loading, it must be declared in @NgModule before use.

Here is an example to briefly introduce the content in @NgModule

//app.module.ts
import { NgModule }  from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
 imports:  [ BrowserModule ],
 providers: [ Logger ],
 declarations: [ AppComponent ],
 exports:  [ AppComponent ],
 bootstrap: [ AppComponent ]
})
export class AppModule { }
  • imports other modules where the classes required by the component template declared in this module are located.

  • providers The creator of the service and added to the global service list, which can be used in any part of the application.

  • declarations declares the view classes owned in this module. Angular has three view classes: components, directives, and pipes.

  • A subset of exports declarations that can be used in component templates of other modules.

  • bootstrap specifies the main view of the application (called the root component), which is the host for all other views. Only the root module can set the bootstrap attribute.

The meaning in the picture: Look at the upper left corner of the picture, the module is used to receive a metadata object that describes the module attributes.

2. Component, template, metadata

This time we will talk about these three points together. Let’s take a look at this code first

//hero-list.component.ts
@Component({
selector: 'hero-list',
templateUrl: './hero-list.component.html',
providers: [ HeroService ]
})
export class HeroListComponent implements OnInit {
/* . . . */
}

Component

A component is a decorator that accepts a configuration object, and Angular creates and displays the component and its views based on this information.

  • selector: A CSS selector that tells Angular to look for the tag in the parent HTML, create and insert the component.

  • templateUrl: The module relative address of the component HTML template. If you use template to write, use the "`" symbol to write HTML code directly.

  • providers: Dependency injection of services required by the component.

template

A template is that piece of HTML code. You can use templateUrl to introduce it from outside, or you can use template`` to write it directly.

metadata

Metadata decorators guide Angular's behavior in a similar way. For example, @Input, @Output, @Injectable, etc. are some of the most commonly used decorators, and their usage will not be expanded here.

What it means in the diagram: Look at the middle of the diagram. Templates, metadata, and components together describe the view.

3.Data binding

A total of four data bindings are shown here. Take a look at the sample code:

//插值表达式 显示组件的hero.name属性的值
  • {{hero.name}}
  • //属性绑定 把父组件selectedHero的值传到子组件的hero属性中 //事件绑定 用户点击英雄的名字时调用组件的selectHero方法
  • //双向绑定 数据属性值通过属性绑定从组件流到输入框。用户的修改通过事件绑定流回组件,把属性值设置为最新的值

    可能大家对各种括号看的眼花了,总结一下:

    • 双花括号是单向绑定,传递的是值。方向是 组件 -> 模板。

    • 方括号是单向绑定,传递的是属性。方向是 父组件 -> 子组件。

    • 圆括号是事件绑定,处理点击等活动(action)。

    • 方括号套圆括号是双向绑定,方向是 组件 模板。

    在图中的意义:看图中间那一块,数据绑定给模板和组件提供数据交互的方式。

    4.指令 (directive)

    严格来说组件就是一个指令,但是组件非常独特,并在 Angular 中位于中心地位,所以在架构概览中,我们把组件从指令中独立了出来。

    我们这里提到的指令有两种类型:

    结构型 structural 指令和属性 attribute 型指令。

    放一下原文证明一下组件确实算是一个指令:

    While a component is technically a directive, components are so distinctive and central to Angular applications that this architectural overview separates components from directives.

    Two other kinds of directives exist: structural and attribute directives.

    结构型指令是 ngFor、ngIf 这种的,通过在 DOM 中添加、移除和替换元素来修改布局。

    属性型指令是 ngModel 这种的,用来修改一个现有元素的外观或行为。

    Angular 还有少量指令,它们或者修改结构布局(例如 ngSwitch ), 或者修改 DOM 元素和组件的各个方面(例如 ngStyle 和 ngClass)。之后我会单独写一篇讲他们用法的文章。

    在图中的意义:看图右上角那一块,组件是一个带模板的指令,只是扩展了一些面向模板的特性。

    5.服务 (service)

    官方文档的概念:

    服务是一个广义范畴,包括:值、函数,或应用所需的特性。服务没有什么特别属于 Angular 的特性。Angular 对于服务也没有什么定义,它甚至都没有定义服务的基类,也没有地方注册一个服务。

    这就像你在 iOS 或者 Android 里单独建了一个类叫 httpService ,封装了网络请求服务一样,不是具体的什么东西,就是一个概念了解下就行。

    在图中的意义:看图左下角角那一块,服务是用来封装可重用的业务逻辑。

    6.依赖注入 (dependency injection)

    依赖注入是提供类的新实例的一种方式,还负责处理类所需的全部依赖。大多数依赖都是服务。 Angular 使用依赖注入来提供新组件以及组件所需的服务。

    比如我们要给某组件导入 HomeService 这个服务,看这段代码:

    constructor(private service: HeroService) { 
     ...
    }

    这个constructor就是构造函数,依赖注入在 constructor 中进行。你也许会觉得前面写上 private、public 之类的很怪,这是 TypeScript 语法比较特殊,习惯就好。

    当 Angular 创建组件时,会首先为组件所需的服务请求一个注入器 injector。我们必须先用注入器 injector 为 HeroService 注册一个提供商 provider。

    看一下下面的代码,意思就是我们必须在 providers 写上才能用

    @Component({
     selector: 'hero-list',
     templateUrl: './hero-list.component.html',
     providers: [ HeroService ]
    })

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    JS的递归实现方法

    JS+canvas绘制饼状统计图

    优化页面加载速度插件InstantClick

    The above is the detailed content of Detailed explanation of the architecture usage of Angular 4.0. For more information, please follow other related articles on the PHP Chinese website!

  • Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

    JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

    Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

    C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor