Angular 2 教程学习笔记
简介
Angular是一款由谷歌开发的前端JavaScript框架,可用于构建富交互式Web应用程序。Angular的第二个版本(Angular2)于2016年发布,它是重新构建的,与其前身有很大的不同。
安装
安装Angular2之前,您需要在本地安装Node.js和npm。接下来,使用以下命令安装Angular CLI:
Copy Codenpm install -g @angular/cli
创建新项目
使用以下命令创建一个新的Angular项目:
Copy Codeng new my-app
cd my-app
组件
组件是Angular中最基本的构建块之一。每个组件都有自己的HTML模板、CSS样式和控制器。在Angular中,组件可以相互嵌套,从而构建出复杂的界面。
以下是一个示例组件的代码:
typescriptCopy Codeimport { Component } from '@angular/core';
@Component({
selector: 'app-hello-world',
template: `
<h1>Hello World!</h1>
<p>This is a sample component.</p>
`,
styles: [`
h1 {
color: red;
}
p {
font-size: 18px;
}
`]
})
export class HelloWorldComponent {
}
模块
在Angular中,模块用于将相关的组件、指令和服务组合在一起。每个Angular应用程序都至少有一个模块,这个模块被称为根模块。
以下是一个示例模块的代码:
typescriptCopy Codeimport { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world.component';
@NgModule({
declarations: [
AppComponent,
HelloWorldComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
服务
服务用于将数据和行为提供给组件。在Angular中,服务通常用于获取数据、执行HTTP请求等任务。
以下是一个示例服务的代码:
typescriptCopy Codeimport { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
getUsers(): Observable<any> {
return this.http.get('https://jsonplaceholder.typicode.com/users');
}
}
路由
路由用于将URL与组件关联起来。在Angular中,路由可以帮助您构建单页应用程序。
以下是一个示例路由的代码:
typescriptCopy Codeimport { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
总结
Angular是一个非常强大的前端JavaScript框架,它可以帮助您快速构建富交互式Web应用程序。在本文中,我们学习了如何安装Angular2,并了解了组件、模块、服务和路由等重要概念。希望这篇文章对您有所帮助!