Filter:过滤器,用于在view中呈现数据时显示为另一种格式;过滤器的本质是一个函数,接收原始数据转换为新的格式进行输出:
function(oldVal){ ... return newVal }
使用过滤器:{{ e.salary | 过滤器名 }}
Angular2.x中,过滤器更名为 “管道(Pipe)”
自定义管道的步骤:
1.创建管道class,实现转换功能
@Pipe({ name:'sex' })
export class SexPipe{
transform(val){ return ....}
}
2.在模块中注册管道
//app.module.ts
declarations:[ SexPipe ]
3.在模板视图中使用管道
{{e.empSex | sex}}
<p [title]="empSex | sex"></p>
说明:管道的transform方法除了val还可以接受其他参数,
调用管道时用冒号为这些参数赋值,例如:{{e.empSex | sex:'en' }}
创建管道对象的简便工具: ng g pipe 管道名
Vue.js中没有预定义管道;Angular提供了几个预定义管道:
1.lowercase:转换为小写
{{ename | lowercase }}
2.uppercase:转换为大写
{{ename | uppercase }}
3.titlecase:转换为首字母大写
{{ename | titlecase }}
4.slice:只显示字符串的一部分
{{ename | slice : 0 : 3 }}
5.json:将JS对象序列化为JSON字符串
{{obj | json }}
6.number:把数字转换为具有指定整数位和小数位的字符串
{{num | number }}
{{num | number:'4.1 -4 '}}
7.currency:把数字转换为货币格式字符串:货币符号+三位一逗号+两位小数位
{{num | currency }}
{{num | currency:'¥' }}
8.date:把数字转换为日期字符串
{{num | date:'yyyy-MM-dd HH:mm:ss' }}
2.创建对象的两种方式
方式一:手工创建式 --------自己创建:let c2 = new Car()
方式二:依赖注入 ---------无需自己new,只需要声明依赖;
服务提供者就会创建被依赖的对象,注入给服务需要者。
3.Angular核心概念之六 -----服务和依赖注入-----抽象&重点!
Service:服务,Aangular认为:组件是与用户交互的一种对象,其中的内容都应该
与用户操作有关系的;而与用户操作无关的内容都应该剥离出去,放在“服务对象”中,
为组件服务;例如日志记录、计时统计、数据服务器访问.....
创建服务对象的步骤:
1.创建服务对象并指定服务提供者
@Injectable({ providedIn:'root' })
export class LogService{ }
2.在组件中声明依赖,服务提供者就会自动注入进来,组件直接使用服务对象即可。
export class XxComponent{
constructor(log:LogService){
//此处的log变量就会被注入为LogService实例
}
}
面试题:前端有哪些异步请求工具?各自的利弊?
1.原生的XHR
2.jQuery.ajax()
3.Axios
4.Angular HttpClient
5.Fetch
使用服务对象时(依赖注入)常见错误:
ERROR NullInjectorError: StaticInjectorError(AppModule)[Myc03Component -> LogService]:
StaticInjectorError(Platform: core)[Myc03Component -> LogService]:
NullInjectorError: No provider for LogService!
指定的服务对象没有服务提供者;
解决方案:
1.保证创建服务对象时指定providedIn:'root'
2.组件声明依赖时服务对象不能写错
4.使用Angular官方提供的服务对象-----HttpClient Service
HttpClient服务对象用于指定的URL发起异步请求,使用步骤:
1.在主模块中导入HttpClient服务所在的模块
//app.module.ts
imports:[ BrowserModule,FormsModule,HttpClientModule ]
2.在需要使用异步请求的组件中声明依赖于HttpClient服务对象,就可以使用该对象发起
异步请求了。
http = null
constructor( http:HttpClient ){
this.http =http
}