Boaz

angular入门篇
**Angular.js学习笔记**基础知识属性插值和数据绑定在很多情况下可以hux替换 插值{{属性}} 数据绑...
扫描右侧二维码阅读全文
23
2020/11

angular入门篇

**

Angular.js学习笔记

**

  • 基础知识

属性插值和数据绑定在很多情况下可以hux替换
插值{{属性}}
数据绑定[]="" innerHTML
CSS类[ngClass]="{,,,}"
循环指令*ngFor="let a of arr; let i=index" trackBy: 方法()返回跟踪值
判断指令*ngIf=""
切换指令[ngSwitch]="" *ngSwitchCase="" *ngSwitchDefault
模板引用变量#var ref-
双向数据绑定表单[(ngModel)]=""    
可拆分扩展[ngModel]="" (ngModelChange)=""
数据对象类public arr:any[]=[]
管道运算符 |
安全导航运算符 item?.name
内置模板函数 类型转换函数$any()
输入输出属性@Input() 是进入组件的门,允许数据流入,而 @Output() 是离开组件的门,允许子组件向外发出数据
事件绑定 (click)=""
  • NgModule模块

此处表达简陋、详细点击下方链接
别再对 Angular Modules 感到迷惑

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports:      [ BrowserModule ], // 导入了本模块中的组件模板所需的类的其它模块
  providers:    [ Logger ],        // 本模块向应用全局贡献的服务。 这些服务能被本应用中的任何部分使用。
  declarations: [ AppComponent ],  // 属于本 NgModule 的组件、指令、管道
                                   // 每个组件都应该(且只能)声明在一个 NgModule 类中。
  exports:      [ AppComponent ],  // 能在其它模块的组件模板中使用的可声明对象的子集、开放导出自己
  bootstrap?:    [ AppComponent ]  // 应用的主视图,称为根组件。它是应用中所有其它视图的宿主。
                                   // Angular 创建它并插入 index.html 宿主页面。
                                   // 只有根模块才应该设置这个 bootstrap 属性。
  entryComponents: [SomeComponent] //Angular 会自动把模块的 bootstrap 中的组件和路由定义中的组件添加到 entryComponents 列表。
    而那些使用不易察觉的ViewComponentRef.createComponent()的方式进行命令式引导的组件仍然需要添加。动态组件加载在除路由器之外的大多数应用中都不太常见。如果你需要动态加载组件,就必须自己把那些组件添加到 entryComponents 列表中。
})
export class AppModule { }

**

  • 服务和数据持久化

**
服务可以实现从服务器获取数据并预处理,验证用户的输入,或者是写日志,在内存中缓存一些可以被全局应用共享的数据或状态,还可以作为组件之间通信的中间介质。
Angular 里将组件和服务区分开,是为了提高模块性和复用性,同时进一步将组件的功能划分出来,让组件更加专注于特定的业务。
数据持久化服务案例

StorageService.service.ts
set(key: string, value: string[]) {     
    localStorage.setItem(key, JSON.stringify(value));  
}
get(key: string) {    
    return JSON.parse(localStorage.getItem(key));  
}  
remove(key: string) {
    localStorage.removeItem(key);  
}

组件内定义

import {StorageService} from '../../services/storage.service';

constructor(public storage: StorageService) {}

this.storage.get();
this.storage.set();

**

  • 生命周期

**
指令和组件的实例有一个生命周期:当 Angular 新建、更新和销毁它们时触发、在触发生命周期事件时会触发唯一钩子方法。
例如:创建组件后调用ngOnInit()方法;
生命周期

  • 钩子用途及时机

    Ionic4中内置的生命周期函数:
    
    
    ionViewWillEnter —当进入一个页面时触发(如果它从堆栈返回)
    
    
    
    ionViewDidEnter —进入后触发
    
    
    ionViewWillLeave —如果页面将离开触发
    
    
    ionViewDidLeave — 在页面离开后触发
    
    
    ionViewWillUnload — 在Angular中没有触发,因为这里你必须使用ngOnDestroy
    
    ngOnChanges()
    当 Angular(重新)设置数据绑定输入属性时响应。 该方法接受当前和上一属性值的 SimpleChanges对象在 ngOnInit() 之前以及所绑定的一个或多个输入属性的值发生变化时都会调用。
    
    
    ngOnInit()
    在 Angular 第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。在第一轮 ngOnChanges() 完成之后调用,只调用一次。
    
    
    ngDoCheck()
    检测,并在发生 Angular 无法或不愿意自己检测的变化时作出反应。在每个变更检测周期中,紧跟在 ngOnChanges() 和 ngOnInit() 后面调用。
    
    
    ngAfterContentInit()
    没当 Angular 把外部内容投影进组件/指令的视图之后调用。第一次 ngDoCheck() 之后调用,只调用一次。
    
    
    ngAfterContentChecked()
    每当 Angular 完成被投影组件内容的变更检测之后调用。ngAfterContentInit() 和每次 ngDoCheck() 之后调用
    
    
    ngAfterViewInit()
    每当 Angular 初始化完组件视图及其子视图之后调用。第一次 ngAfterContentChecked() 之后调用,只调用一次。
    
    
    ngAfterViewChecked()
    每当 Angular 做完组件视图和子视图的变更检测之后调用。ngAfterViewInit() 和每次 ngAfterContentChecked() 之后调用。
    
    
    ngOnDestroy()
    没当 Angular 每次销毁指令/组件之前调用并清扫。 在这儿反订阅可观察对象和分离事件处理器,以防内存泄漏。在 Angular 销毁指令/组件之前调用。
    

**

  • 父子组件通信传值

**
监听数据变化

import {
  SimpleChanges
} from '@angular/core';
 @Input() placeLngLat: SimpleChanges;
  ngOnChanges(changes: SimpleChanges) {
    if (changes.placeLngLat) {
      console.log('我变了')
  }

Ionic pop传递参数

返回页面的相关代码如下:

this.navCtrl.getPrevious().data.myNewKey = someData;
this.navCtrl.pop();

上一页的相关代码如下:

ionViewWillEnter() {
   this.myNewData = this.navParams.get('myNewKey')|| null;
}

- 父组件@Input给子组件传值

1、组件传递变量和方法home.component.html

<app-header [msg]="msg" [title]="title" [run]="run" [home]="this"></app-header>

2、子组件中需要引入 Input,用来接收父组件传过来的数据。

@Input() msg: any;

@Input() title: any;

@Input() run: any;
/*//获取home组件所有内容*/
@Input() home: any;

 getParentWay() {
// alert(this.run());
alert(this.home.run());

}

3、总结
1.父组件页面嵌套子组件页面,将属性和方法存放在子组件声明中;
2.子组件引入 Input 模块;
3.子组件通过@Input 获取子组件声明中存放的属性和方法;

- 子组件ViewChild给父组件传值

1、父组件中子组件声明news.component.html

<app-footer #footerComponent></app-footer>

2、父组件获取子组件全部内容news.component.ts

@ViewChild('footerComponent') footer;
this.footer.msg;
this.footer.run();

3、总结
1.父组件页面嵌套子组件页面,子组件声明时需要定义一个名称来代指子组件;
2.父组件引入 ViewChild 模块;
3.父组件通过@ViewChild 获取子组件的全部内容;

- 子组件@Output给父组件传值

1、父组件嵌套子组件声明

<app-footer (outter)="run($event)"></app-footer>

2、子组件封装数据

@Output() private outter = new EventEmitter();
this.outter.emit('我是footer组件的数据');

3、小结
1.子组件引入 Output、EventEmitter 模块;
2.子组件将要传输的数据封装在 outter 中;
3.父组件页面嵌套子组件页面,子组件声明时需要将 outter 指向父组件中的某个方法,注意接收数据;

- 父子组件相互传值

1、子组件
size 的初始值来自属性绑定的输入值。单击按钮可在最小值/最大值范围内增大或减小 size,然后带上调整后的大小发出 sizeChange 事件。

@Input() size: number | string;
@Output() sizeChange = new EventEmitter<number>();

this.sizeChange.emit(this.size);

2、父组件

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>
或者双向数据绑定、效果一样
<app-sizer [(size)]="fontSizePx"></app-sizer>    

**

  • 数据交互

**

- Get获取数据

1、在app.module.ts中引入 HttpClientModule

import {HttpClientModule} from '@angular/common/http';
imports: [    
BrowserModule,    
HttpClientModule,    
HttpClientJsonpModule
]

2、调用接口获取数据

import {HttpClient, HttpHeaders} from '@angular/common/http';
constructor(public client: HttpClient) {}
getData() {       
    var api=''; this.client.get(api).subscribe((data: any) => {   
        this.dataList = data.members;    
    });  
}

- Post获取数据

import {HttpClient, HttpHeaders} from '@angular/common/http';
constructor(public client: HttpClient) {}
doPost() {
    const header = { headers: new HttpHeaders({ 'ContentType': 'application/json' }) };
    let url = 'http://localhost:8080/testPostBody';    
    this.client.post(url, {'uname': 'hresh', 'age': 24 }
    , header).subscribe((response: any) => 
    {      
        console.log(response);    
    });
}

- jsonp获取数据

getJsonpData() {
    var api = 'http://a.itying.com/api/productlist';
    this.client.jsonp(api, 'callback').subscribe((data) => {
        console.log(data);
    })
}

- 第三方模块axios获取数据

1、安装axios

npm install axios

2、配置服务文件httpservice.service.ts

import {Injectable} from '@angular/core';
import axios from 'axios';
import {Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class HttpserviceService {
  constructor() {}  //可以返回Promise对象,也可以使用Rxjs,根据个人习惯
  axiosGet(api) {
    return new Promise((resolve, reject) => {
      axios.get(api).then(function(res) {
        resolve(res);
      });
    });
  }
}

3、引入 httpservice 并在构造函数声明

import { HttpserviceService } from '../../services/httpservice.service';  
constructor(public client: HttpClient, public httpservice: HttpserviceService) {  }
//通过第三方模块获取服务器数据  
getAxiosData() {
  var api = '';
  let axiosObj = this.httpservice.axiosGet(api);
  axiosObj.then((data) => {
    console.log(data);
  })
}

4、直接引入axios

import axios from 'axios';

ngOnInit(){
   axios.get("").then(res=>{
     console.log(res)
   }).catch((err)=>{
     console.log(err);
   }).finally(()=>{
     console.log('执行完了');
   });
 }

const httpOptions={headers:new HttpHeaders({'Content-Type':'application/json'})}
axios.post("", {}, httpOptions).subscribe((response:any)) => {
    console.log(response);
}
Last modification:January 6th, 2021 at 04:52 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment