初始化
1.安裝cli: npm install -g @angular/cli
2.安裝目錄及初始化: ng new my-app
3.啟動開發(fā)服務(wù)器 cd 到當(dāng)前目錄運行: ng serve (--open或-o)
常用命令
1.創(chuàng)建一個名為 heroes 的新組件: ng (generate 或 g) component heroes
注:組件可以指定目錄如: component/heroes
2.創(chuàng)建類似于vuex的服務(wù)如: ng g service services/common
用法:
1.app.module.ts里引入服務(wù)
//引入服務(wù)
import { StorageService } from './services/storage.service';
//引用http(可選,用就引入)
import { HttpClientModule } from '@angular/common/http';
//引入form(可選籽腕,用就引入)
import { FormsModule } from '@angular/forms';
@NgModule({
? ...
? imports: [
? ? FormsModule, //引入form (可選嗡呼,用就引入)
? ? HttpClientModule //引入http (可選,用就引入)
? ],
? providers: [StorageService], //服務(wù)
})
2.直接拋出定義方法即可
import { HttpClient } from '@angular/common/http';
@Injectable({
? providedIn: 'root'
})
export class CommonService {
? public domain = "http://xxx.com/";
? constructor(public http: HttpClient) { } //引入http方法
? get(api: string) { //定義方法
? ? return new Promise((resolve, reject) => {
? ? ? //http用法
? ? ? this.http.get(this.domain + api).subscribe((response) => {
? ? ? ? resolve(response)
? ? ? })
? ? });
? }
}
3.引用頁面用法
import { CommonService } from '../../services/common.service';
@Component({
? selector: 'app-home',
? templateUrl: './home.component.html',
? styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
? public list: any[] = [];
? constructor(public common: CommonService) {} //類初始化引用
? ngOnInit() {
? ? //調(diào)用
? ? this.common.get("api/productlist").then((response: any) => {
? ? ? this.list = response.result;
? ? })
? }
}
模塊化開發(fā)設(shè)置自定義模塊
命令:ng g module module/user (加 --routing 是給模塊里建路由用皇耗,實現(xiàn)模塊懶加載)
1.模塊創(chuàng)建完需要暴露出去:在創(chuàng)建的模塊module里的?
@NgMoule({
...
exports:[xx(模塊名)]
})
注:模塊里創(chuàng)建的模塊除非exports里暴露出去的組件南窗,否則組件沒法在全局引用
2.在app.module.ts里引入模塊先頭部import {xx} from '路徑' 引入在把名字加到?
@NgMoule({
...
imports:[xx(模塊名)]
})
給模塊里建組件:ng g component module/user/component/home
注:創(chuàng)建服務(wù)或其他也是: ng g service module/user/services/common
模塊路由懶加載
命令:ng g module module/user --routing
1.app-routing里引入
const routes: Routes = [
? //模塊懶加載
? { path: 'login', loadChildren: './module/login/login.module#LoginModule' },
? //設(shè)置沒有路由默認(rèn)值
? { path: '**', redirectTo: 'login' }
];