angular4项目搭建总结

项目搭建

步骤1:设置开发环境

首先安装Node.js和npm,安装地址(在终端/控制台窗口中运行命令 node -vnpm -v查看版本 )

然后全局安装 Angular CLI

npm install -g @angular/cli

步骤2:创建新项目

ng new SoftH

步骤3:启动项目

cd SoftH
ng serve --open 或者 npm start(推荐)

步骤 4:创建一个组件或者模块或者服务

(模块) ng g m [module-name]   a-m
(组件) ng g c [component-name] a-c
(管道) ng g pipe [pipe-name] a-pipe
(服务) ng g s [service-name] a-s
(路由模块) 暂时无法用命令创建,需手动创建,输入a-m-r快速创建

基础设置

sass设置

angular-cli.json文件里

 "defaults": {
     "styleExt": "sass",
      "component": {}
  }

设置完sass之后,在组件里就必须用styleUrls,不能直接用Styles写样式了

hash路由

RouterModule.forRoot(routes, { useHash: true });使用hash路由,后端不用修改配置,这样比较方便,省去很多麻烦(具体原理,我也不清楚)

http

error: No provider for Http

使用http相关API,需要注入HttpModule

import { HttpModule } from '@angular/http';

declare

引入第三方js库(typings.d.ts)

路由相关

RouterModule

forRoot 定义的根路由(appRoutingModule)在项目中只出现一次

forChild定义子路由

Error: StaticInjectorError(AppModule)
[RouterOutlet -> ChildrenOutletContexts]:
StaticInjectorError(Platform: core)[RouterOutlet -> ChildrenOutletContexts]: 
NullInjectorError: No provider for ChildrenOutletContexts!

报这个错应该把根路由forChild=>forRoot

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})

.angular-cli.json基础配置

详见此篇文章

路由路径设置

routes path前面不能加/

angular4提供了路由懒加载

AppRoutingModule

{ 
   path: 'external-agency/:externalId', 
   canActivate: [AuthGuardService], 
   loadChildren: 'app/components/external-agency/external-agency.module#ExternalAgencyModule'
  }

注意看惰性加载的语法:loadChildren 后面紧跟着一个字符串,它指向模块路径,然后是一个 #,然后是该模块的类名。当路由为external-agency/13时,会自动去ExternalAgencyModule=>ExternalAgencyRoutingModule中,不用单独用import引入ExternalAgencyModule
ExternalAgencyRoutingModule

{ path: '', redirectTo: 'home', pathMatch: 'full' },  //此处home表示当路由为空时,路由重定向为external-agency/13/home(AgencyHomeComponent),如果是/home,路径是回根部,重定向为home
  {
    path: '', component: ExternalAgencyComponent, //path为空,因为AppRoutingModule已经设置好路径了,此路由相当于是ExternalAgencyModule的子路由
    children: [
      { path: 'home', component: AgencyHomeComponent }, //此路由为ExternalAgencyComponent组件的子路由,在ExternalAgencyComponent中一定有一个<router-outlet></router-outlet>
      { path: 'course', component: CourseListComponent },
      { path: 'word', component: WordListComponent },
      { path: 'teacher', component: TeacherListComponent },
    ]
  },

引入插件库

引入插件库都要做的两步:

1.安装组件

npm i 插件名 --save

2.引入样式

修改 .angular-cli.json 文件的 styles 列表

...
  "styles": [
    "../node_modules/....css"
  ],
  "scripts": [
    "../node_modules/....js"
  ],
...

jquery

1.安装插件

npm i jquery --save

npm i @types/jquery --save-dev

2.引入样式

.angular-cli.json 中引入 jquery.min.js

"scripts": ["../node_modules/jquery/dist/jquery.min.js"

3.引用

此刻就可以局部引用jquery

import * as $ from 'jquery';

如果要在全局引用,需要在typings.d.ts

/* SystemJS module definition */
declare var module: NodeModule;
declare var $: any;   
declare var jQuery: any;  
interface NodeModule {
  id: string;
}

大多数情况都会报 无法重新声明块范围变量“jQuery”和“$” 的错误,只需要去node_modules\@types\jquery\index.d.ts注释掉以下两行代码

 declare const jQuery: JQueryStatic;
 declare const $: JQueryStatic;

bootstrap4

1.安装插件

npm i bootstrap --save

npm i @types/bootstrap --save-dev

2.引入样式

.angular-cli.json文件中引入bootstrap4

"styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.css"   //必要时候可以引入bootstrap-theme.css
],
"scripts": [
    "../node_modules/bootstrap/dist/js/bootstrap.js"
],

NG-ZORRO

这是angular4常见的UI插件库,可能与bootstrap有冲突,但冲突不大。官网(有些公司网络限制),替代网站

1.安装插件

npm i ng-zorro-antd --save

或者

yarn add ng-zorro-antd

2.引入模块

AppModule中引用NgZorroAntdModule

import { NgZorroAntdModule } from 'ng-zorro-antd';
//注册语言包 
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';
@NgModule({
  ...
  imports: [
    NgZorroAntdModule.forRoot()
  ],
  ...
})

3.引入样式

swiper

官网(方法一)

方法二:

npm i --save angular2-useful-swiper

npm i --save [email protected] //此种方法只支持3版本,运用方法也不同

引用样式

  "styles": [
        "styles.css",
        "../node_modules/swiper/dist/css/swiper.css"        
    ],
    "scripts": [
        "../node_modules/swiper/dist/js/swiper.js"                
    ],

html中:

<swiper [config]="config">
    <div class="swiper-wrapper">
         <div class="swiper-slide">Slide 1</div>
          <div class="swiper-slide">Slide 2</div>
          <div class="swiper-slide">Slide 3</div>
          <div class="swiper-slide">Slide 4</div>
    </div>
     <!-- Add Pagination -->
     <div class="swiper-pagination"></div>
     <!-- Add Arrows -->
     <div class="swiper-button-next"></div>
     <div class="swiper-button-prev"></div>
</swiper>

ts中:

export class MyComponent implements OnInit {
    config: SwiperOptions = {
        pagination: '.swiper-pagination',
        paginationClickable: true,
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        spaceBetween: 30
    };

强调:一定要引用import { SwiperModule } from 'angular2-useful-swiper';

其他

有时候我们写一个路径,包括img、iframe、a等等,angular会默认在路径前面添加一个unsafe,此刻需要做如下处理:

在ts中

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
export class AppDownloadComponent implements OnInit {
   openUrl: SafeResourceUrl;
   this.openUrl = this.sanitizer.bypassSecurityTrustResourceUrl(需要处理的路径);
}

我遇到该问题是在做一个app下载功能时,iphone客户端下载路径是一个plist路径,因此必须做安全路径处理!!!

猜你喜欢

转载自blog.csdn.net/Lobove_code/article/details/80494355
今日推荐