angular7.0+ngx-weui公众号开发,开发及框架搭建(二)
接着上章节打开webstorm开发工具
1.webstorm
使用webstorm打开项目如下图
2.项目开发在手机端和web端要加一句话<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">放在src的index.html文件下。项目还要在手机端调试所以在运行的时候我们的http://localhost:4200/就没有用了,毕竟谷歌浏览器可以模仿手机,但还是和微信公众号有差别,所以修改package.json如下图所示
3.点击webstorm的npm,右键start,点击run start,在浏览器中就是以ip地址访问的了如下图所示。
2.框架搭建
1.上面都是基础玩的,主要让刚用的人玩的,下面开始框架搭建(是我朋友的然后我按自己理解进行改动)觉得不行的可以提哦。
2.我们先来创建common自定义公用组件和指令的core.module.ts 创建后如下图所示
[code]import {NgModule, ModuleWithProviders} from '@angular/core'; import {CommonModule, HashLocationStrategy, LocationStrategy} from '@angular/common'; import {ReactiveFormsModule, FormsModule} from '@angular/forms'; import {HttpClientModule} from '@angular/common/http'; import {LocalStorage} from '../utils/local.storage'; import {SessionStorage} from '../utils/session.storage'; /** * 自定义组件 */ const components = [ ]; /** * 自定义指令 */ const directives=[ ] const providers=[ LocalStorage, SessionStorage, {provide: LocationStrategy, useClass: HashLocationStrategy} ]; @NgModule({ imports: [ CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule ], declarations: [ ...components, ...directives ], exports: [ CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule, ...components, ...directives ] }) export class CoreModule { static forRoot(): ModuleWithProviders { return { ngModule: CoreModule, providers: [ ...providers ] }; } }
3.到这边webstorm肯定报错少了 LocalStorage, SessionStorage这两个TS文件所以我们要到,utils目录下创建local.storage.ts, session.storage.ts两个文件,在创建一个util.ts公用的方法,在app.module.ts修改如下:
[code]import {Injectable} from '@angular/core'; @Injectable() export class LocalStorage { public localStorage: any; constructor() { if (!localStorage) { throw new Error('Current browser does not support Local Storage'); } this.localStorage = localStorage; } /** * 保存字符串 * @param {string} key * @param {string} value */ public set(key: string, value: string): void { this.localStorage[key] = value; } /** * 获取保存的字符串 * @param {string} key * @returns {string} */ public get(key: string): string { return this.localStorage[key] || ''; } /** * 保存对象 * @param {string} key * @param value */ public setObject(key: string, value: any): void { this.localStorage[key] = JSON.stringify(value); } /** * 获取保存对象 * @param {string} key * @returns {any} */ public getObject(key: string): any { return JSON.parse(this.localStorage[key] || null); } /** * 移除保存的数据 * @param {string} key * @returns {any} */ public remove(key: string): any { this.localStorage.removeItem(key); } }
[code]import {Injectable} from '@angular/core'; @Injectable() export class SessionStorage { public sessionStorage: any; constructor() { if (!sessionStorage) { throw new Error('Current browser does not support Session Storage'); } this.sessionStorage = sessionStorage; } /** * 保存字符串 * @param {string} key * @param {string} value */ public set(key: string, value: string): void { this.sessionStorage[key] = value; } /** * 获取保存的字符串 * @param {string} key * @returns {string} */ public get(key: string): string { return this.sessionStorage[key] || ''; } /** * 保存对象 * @param {string} key * @param value */ public setObject(key: string, value: any): void { this.sessionStorage[key] = JSON.stringify(value); } /** * 获取保存对象 * @param {string} key * @returns {any} */ public getObject(key: string): any { return JSON.parse(this.sessionStorage[key] || null); } /** * 移除保存的数据 * @param {string} key * @returns {any} */ public remove(key: string): any { this.sessionStorage.removeItem(key); } /** * 移除所有缓存并退出 * @param {string} key * @returns {any} */ public clear(): any { this.sessionStorage.clear(); } }
[code] export class Util { static toImg(){ return '../../../../assets/img/'; } /** * 生成随机字符串 * @param version * @returns {string} */ static getCode(a:number){ let num=''; for(let i=0;i<a;i++){ num+=Math.floor(Math.random()*10); } return } /** * 格式化时间 * @param str */ static fomart(str: string) { let date=new Date(); if(str===null||str===""||str==="undefined"){ }else{ date = new Date(str.replace(/-/g,'/')); } let hours=date.getHours().toString(); if(hours.length<2){ hours=' 4000 0'+hours; } let minutes=date.getMinutes().toString(); if(minutes.length<2){ minutes='0'+minutes; } let seconds=date.getSeconds().toString(); if(seconds.length<2){ seconds='0'+seconds; } let getMonth=(date.getMonth() + 1).toString(); if(getMonth.length<2){ getMonth='0'+getMonth; } let getDate=date.getDate().toString(); if(getDate.length<2){ getDate='0'+getDate; } return date.getFullYear() + '-' + getMonth + '-' + getDate + ' ' + hours + ':' + minutes + ':' + seconds; } /** * 格式化时分秒 * @param {string} str * @returns {string} */ static fomartHour(str: string) { let date=new Date(); if(str===null||str===""||str==="undefined"){ }else{ date = new Date(str.replace(/-/g,'/')); } let hours=date.getHours().toString(); if(hours.length<2) { hours = '0' + hours; } let minutes=date.getMinutes().toString(); if(minutes.length<2){ minutes='0'+minutes; } let seconds=date.getSeconds().toString(); if(seconds.length<2){ seconds='0'+seconds; } return hours + ':' + minutes + ':' + seconds; } /** * 格式化年月日 * @param str * @returns {string} */ static fomartDay(str:string) { let date=new Date(); if(str===null||str===""||str==="undefined"){ }else{ date = new Date(str.replace(/-/g,'/')); } let getMonth=(date.getMonth() + 1).toString(); if(getMonth.length<2){ getMonth='0'+getMonth; } let getDate=date.getDate().toString(); if(getDate.length<2){ getDate='0'+getDate; } return date.getFullYear() + '-' + getMonth + '-' + getDate; } /** * 格式化月日 * @param str * @returns {string} */ static fomartDayDto(str: any) { let date=new Date(); if(str===null||str===""||str==="undefined"){ }else{ date = new Date(str.replace(/-/g,'/')); } return (date.getMonth() + 1) + '-' + date.getDate(); } /** * 格式化年月 * @param str * @returns {string} */ static formartMonth(str:any){ let date=new Date(); if(str===null||str===""||str==="undefined"){ }else{ date = new Date(str.replace(/-/g,'/')); } return date.getFullYear()+'-'+(date.getMonth() + 1); } /** * 格式化年 * @param str * @returns {string} */ static formartYear(str:any){ let date=new Date(); if(str===null||str===""||str==="undefined"){ }else{ date = new Date(str.replace(/-/g,'/')); } return date.getFullYear(); } /** * 非空判断 * @param str * @returns {string} */ static empty(str: string) { if (str != null && str !== '' && str !== undefined) { return true; } else { return false; } } /** * 判断是否是闰年 * @param year */ static isYear(year: number): boolean { return (year % 100 === 0) ? ((year % 400 === 0) ? true : false) : ((year % 4 === 0) ? true : false); } /** * 处理获取时间格式 * @param time * @returns {string} */ static timeList(time) { let timeList = ''; if (time !== null || time !== '' || time !== 'undefined') { timeList = time.split("T")[1].split("+")[0]; } else { timeList = time; } return timeList; } /** * 对象转map * @param obj * @returns {Map<any, any>} */ static objToStrMap = (obj) => { let strMap = new Map(); for (let k of Object.keys(obj)) { strMap.set(k, obj[k]); } return strMap; }; static emptyLine = (str) => { if(str===null||str===""||str==="undefined"){ return "--" }else{ return str; } }; static getNowTime(date) { return `${date.getFullYear()}-${this.format(date.getMonth() + 1)}-${this.format(date.getDate())} ${this.format(date.getHours())}:${this.format(date.getMinutes())}:${this.format(date.getSeconds())}` } static format(value) { if (value < 10) { return "0" + value; } else { return value; } } static getNowDate(date) { return `${date.getFullYear()}-${this.format(date.getMonth() + 1)}-${this.format(date.getDate())}` } static getTime(date) { return `${this.format(date.getHours())}:${this.format(date.getMinutes())}:${this.format(date.getSeconds())}` }; static arrayDuplicateRemoval(colorArr:Array<string>):Array<string>{ //随机颜色 let res:Array<string> = []; let json = {}; for(let i = 0; i < colorArr.length; i++){ if(!json[colorArr[i]]){ res.push(colorArr[i]); json[colorArr[i]] = 1; } } return res; } static IdCardValid(value: string):boolean{ if (18 === value.length) { //18位身份证号码 if (value.charAt(17) !== this.IdCardIsp(value)) { return false; } else { return true; } } else { return false; } } static IdCardIsp(value:string):any { if (value.length !== 18){ return false; } let x = 0; for (let i = 18; i >= 2; i--){ x = x + (this.square(2, (i - 1)) % 11) * parseInt(value.charAt(19 - i - 1).toString(),10); } x %= 11; let y = (12 - x).toString(); if (x === 0){ y = '1'; } if (x === 1){ y = '0'; } if (x === 2){ y = 'X'; } return y; } static square(x, y) { let i = 1; for (let j = 1; j <= y; j++) { i *= x; } return i; } //手机号验证 static isPhoneNumber(value:string):boolean{ if((/^1(3|4|5|7|8)\d{9}$/.test(value))){ return true; }else{ return false; } } static dateFormat(timestamp, format){ const date =new Date(timestamp); let date1 = { "M+": date.getMonth() + 1, "d+": date.getDate(), "h+": date.getHours(), "m+": date.getMinutes(), "s+": date.getSeconds(), "q+": Math.floor((date.getMonth() + 3) / 3), "S+": date.getMilliseconds() }; if (/(y+)/i.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); } for (let k in date1) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? date1[k] : ("00" + date1[k]).substr(("" + date1[k]).length)); } } return format; } }
4.在model目录里面创建base-resp.ts如下图所示
[code]export interface BaseResp<T> { code: number; data: T; }
5.在server服务目录下创建net-service-httpclient.ts文件 ,如下图所示
[code]import {HttpClient, HttpHeaders} from '@angular/common/http'; import {HttpParams} from '@angular/common/http/src/params'; import {Observable} from 'rxjs'; import {environment} from '../../environments/environment'; export abstract class NetServiceHttpclient { protected baseUrl = environment.config.apiUrl; protected constructor(public httpClient: HttpClient) { } protected get headers(): HttpHeaders { //const token: string = sessionStorage.getItem('token')===null?'':sessionStorage.getItem('token'); const headers = new HttpHeaders({ 'Accept':'application/json', 'Content-Type': 'application/json' //'Authorization': token }); return headers; } protected get headersFile(): HttpHeaders { //const token: string = sessionStorage.getItem('token')===null?'':sessionStorage.getItem('token'); const headers = new HttpHeaders({ 'Accept':'application/json', //'Authorization': token }); return headers; } /** * GET * @param relativeUrl * @param params * @param headers */ protected get<T>(relativeUrl: string, params?: HttpParams | { [param: string]: string | string[] }, headers?: HttpHeaders): Observable<T> { return this.httpClient.get<T>(this.baseUrl + relativeUrl, { headers: headers || this.headers, params: params }); } /** * Post * @param relativeUrl * @param body * @param params * @param headers */ protected post<T>(relativeUrl: string, body?: any, params?: HttpParams | { [param: string]: string | string[] }, headers?: HttpHeaders): Observable<T> { return this.httpClient.post<T>(this.baseUrl + relativeUrl, body, { headers: headers || this.headers, params: params }); } /** * Post * @param relativeUrl * @param body * @param params * @param headers */ protected postFile<T>(relativeUrl: string, body?: any, params?: HttpParams | { [param: string]: string | string[] }, headers?: HttpHeaders): Observable<T> { return this.httpClient.post<T>(this.baseUrl + relativeUrl, body, { headers: headers || this.headersFile, params: params }); } /** * GET * @param relativeUrl * @param params * @param headers */ protected getMap<T>(relativeUrl: string, params?: HttpParams | { [param: string]: string | string[] }, headers?: HttpHeaders): Observable<T> { return this.httpClient.get<T>(relativeUrl); } /** * Put * @param relativeUrl * @param body * @param params * @param headers */ protected put<T>(relativeUrl: string, body?: any, params?: HttpParams | { [param: string]: string | string[] }, headers?: HttpHeaders): Observable<T> { return this.httpClient.put<T>(this.baseUrl + relativeUrl, body, { headers: headers || this.headers, params: params }); } /** * Delete * @param relativeUrl * @param params * @param headers */ protected delete<T>(relativeUrl: string, params?: HttpParams | { [param: string]: string | string[] }, headers?: HttpHeaders): Observable<T> { return this.httpClient.delete<T>(this.baseUrl + relativeUrl, { headers: headers || this.headers, params: params }); } /* * export * */ protected export(relativeUrl: string, body?: any, fileName?:string, fileType?:any){ this.httpClient.request("post",this.baseUrl + relativeUrl, {body: body, observe: 'response',responseType:'blob', headers: this.headers}) .subscribe(result => { const uA = window.navigator.userAgent;//判断浏览器内核 const isIE = /msie\s|trident\/|edge\//i.test(uA) && !!("uniqueID" in document || "documentMode" in document || ("ActiveXObject" in window) || "MSInputMethodContext" in window); const data=result.body; const blob = new Blob([data], {type: fileType||"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); const a = document.createElement('a'); const objectUrl = URL.createObjectURL(blob); a.setAttribute('style', 'display:none'); a.setAttribute('href', objectUrl); a.setAttribute('download', fileName); //此处是为了兼容火狐点击事件; document.body.appendChild(a); if (isIE) { // 兼容IE11无法触发下载的问题 navigator.msSaveBlob(new Blob([data]),a.download); } else { a.click(); } /*// 触发下载后再释放链接 a.addEventListener('click', function() { URL.revokeObjectURL(a.href); document.getElementById('download').remove(); }); a.click(); URL.revokeObjectURL(objectUrl);*/ }); } }
6.配置environments目录下environments.ts(这个代表测试)和environments.prod.ts(这个代表生产) ,如下图所示
[code]export const environment = { production: false, config:{ apiUrl:'这是测试连接' } };
[code]export const environment = { production: true, config:{ apiUrl:'这是生产连接' } };
3.到这边框架已经搭建完成了,第三章将开始写代码
- Angular开发实践(一):环境准备及框架搭建
- Nodejs+express+angularjs+mongodb搭建前端项目框架NJBlog
- 【Hibernate框架开发之一】搭建Hibernate环境并成功运行第一个项目HelloHibernate并解决3个常出现的运行问题;
- HTML5 APP开发环境的框架搭建
- Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架
- 以太坊 DApp 开发入门实战! 用Node.js和truffle框架搭建——区块链投票系统!
- sonne_game网站开发02spring+mybatis框架搭建
- 基于Flask框架的Python web程序的开发实战 <一> 环境搭建
- C++开发人脸性别识别教程(7)——搭建MFC框架之界面绘制
- H5开发:搭建 AngularJS+Ionic+Cordova 开发环境
- Tomcat7.0开发环境搭建
- springMVC学习笔记---day02 springMVC+spring+mybatis整合开发框架搭建
- 前端开发环境搭建 Grunt Bower、Requirejs 、 Angular
- 使用Angular 4、Bootstrap 4、TypeScript和ASP.NET Core开发的Apworks框架案例应用
- 基于dubbo的分布式项目框架搭建 开发工具idea (springboot+dubbo+zookeeper+redis+rabbitmq+基于Swagger2的restful api) --(一)
- HTML5 APP开发环境的框架搭建
- 利用Angular实现多团队模块化SPA开发框架
- 自己动手搭建ava通用开发框架之三—通用权限模型建立
- 简易Mvp+RxJava2+Retrofit2 搭建一个属于自己的开发框架
- weex 项目开发(四)项目框架搭建 及 自定义 TabBar 组件