angular使用NG ZORRO来构建博客展示项目(简单实现展示页面)

返回目录

使用 NG ZORRO

在上一篇文章中,我们已经安装了NG ZORRO,并在跟模块中引入了,在子模块中使用还需要再次引入。

编辑layout模块中的header组件

在layout.module.ts中引入NG ZORRO

import { NgZorroAntdModule } from 'ng-zorro-antd';

  imports: [
    CommonModule,
    RouterModule,
    NgZorroAntdModule
  ],

编辑header.component.html简单布局

<div class="header">
  <div class="logo">
    <img src="../../../assets/img/logo.png"/>
  </div>
  <div class="top-menu">
    <ul nz-menu [nzMode]="'horizontal'"  style="line-height: 64px;">
      <li nz-menu-item><i class="anticon anticon-home"></i> 主页</li>
      <li nz-menu-item routerLink="blog"><i class="anticon anticon-appstore"></i> 博客</li>
      <li nz-submenu>
        <span title><i class="anticon anticon-setting"></i> 秘密</span>
        <ul>
          <li nz-menu-item>秘密1 </li>
          <li nz-menu-item>秘密2 </li>
        </ul>
      </li>
      <li nz-menu-item><i class="anticon anticon-user"></i>神马</li>
      <li nz-menu-item><i class="anticon anticon-mail"></i>约</li>
    </ul>
  </div>
</div>

在header.component.css中简单调整下样式

.logo {
  width: 120px;
  height: 66px;
  margin-left: 50px;
  float: left;
}
.logo img{
  height: 100%;
  width: auto;
}
.top-menu{
  float: right;
  margin-right: 50px;
}
.header{
  height: 66px;
  border-bottom: 1px solid #e9e9e9;
}

看看效果展开二级菜单的时候报错了,说我们要包含"BrowserAnimationsModule" 或者"NoopAnimationsModule"模块

展开二级菜单的时候报错了

在app.module.ts中引用

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

  imports: [
    RouterModule,
    BrowserModule,
    NgZorroAntdModule.forRoot(),
    RoutesModule,
    BrowserAnimationsModule
  ],
这次好了

简单编辑下footer组件

<div class="footer">
  易兒善©2017
</div>
.footer{
  background-color: darkgray;
  padding: 20px 50px;
  width: 100%;
  text-align: center;
}

创建服务

要和后台交互,我们就需要有http请求,需要用到angular的http模块。从angular2到现在的angular5http模块也有些变化。
我是这样设计的,把api请求封装成一个基类,然后在此基础上封装一个针对后台apb框架的基类,最后才是我们应用所需要的api请求数据组件。

这两个并没有设计成core模块的组件,但是也放在这里,不知道放在哪里合适。有的可以不用设计成angular模块或者组件,初学者真烦恼

api-base-service.ts

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import * as moment from 'moment';
import { environment } from '../../../environments/environment';

/**
 * 封装HttpClient,主要解决:
 * + 优化HttpClient在参数上便利性
 * + 统一实现 loading
 * + 统一处理时间格式问题
 */
export abstract class ApiBaseService {
  constructor(protected http: HttpClient) { }

  private _loading = false;

  /** 是否正在加载中 */
  get loading(): boolean {
    return this._loading;
  }

  parseParams(params: any): HttpParams {
    let ret = new HttpParams();
    if (params) {
      // tslint:disable-next-line:forin
      for (const key in params) {
        let _data = params[key];
        // 将时间转化为:时间戳 (秒)
        if (moment.isDate(_data)) {
          _data = moment(_data).unix();
        }
        ret = ret.set(key, _data);
      }
    }
    return ret;
  }

  private begin() {
    console.time('http');
    this._loading = true;
  }

  private end() {
    console.timeEnd();
    this._loading = false;
  }

  /** 服务端URL地址 */
  get SERVER_URL(): string {
    return environment.SERVER_URL;
  }

  /**
   * GET请求
   *
   * @param {string} url URL地址
   * @param {*} [params] 请求参数
   */
  get(url: string, params?: any): Observable<any> {
    this.begin();
    return this.http
      .get(url, {
        params: this.parseParams(params)
      })
      .do(() => this.end())
      .catch((res) => {
        this.end();
        return res;
      });
  }

  /**
   * POST请求
   *
   * @param {string} url URL地址
   * @param {*} [body] body内容
   * @param {*} [params] 请求参数
   */
  post(url: string, body?: any, params?: any): Observable<any> {
    this.begin();
    return this.http
      .post(url, body || null, {
        params: this.parseParams(params)
      })
      .do(() => this.end())
      .catch((res) => {
        this.end();
        return res;
      });
  }

abp-api-service.ts

import {ApiBaseService} from "./api-base-service"
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';


/**
 * 进一步封装HttpClient,主要解决:
 * 后台apb框架返回数据的解析
 */
export abstract class AbpApiService extends ApiBaseService {
  constructor(protected http: HttpClient) {
    super(http);
  }

  abpGet<T>(url: string, params ? : any): Observable<any> {
    return this.get(url,params).map(r=>{
      return this.process<T>(r);
    });
  }
  abpPost<T>(url: string, body?: any, params?: any): Observable<any> {
    return this.post(url,body,params).map(r=>{
      return this.process<T>(r);
    })
  }
  private process<T>(r:any):any{
    const data = r as Result;
    if(data.success){
      return data.result as T;
    }else {
      console.error(data.error);
      throw data.error;
    }
  }
}

// 后台返回的结构体
export  class Result{
  success:boolean;
  error:any;
  result:any;
}

blog.service.ts,这个写的是组件,并在模块中声明了
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import {AbpApiService} from "../../core/services/abp-api-service"
import {environment} from "../../../environments/environment"

const blogApiUrl ={
  getNoteList :environment.SERVER_URL+"/api/services/app/NoteServer/GetPreNoteList",
  getNote:environment.SERVER_URL+"/api/services/app/NoteServer/GetNote",
  like:environment.SERVER_URL+"/api/services/app/NoteServer/Like"
};
// 要使该服务可以依赖注入,需要加上下面这个标签,并且在模块中声明
@Injectable()
export class BlogService extends AbpApiService{

  constructor(protected http: HttpClient) {
    super(http)
  }

  public GetNoteList(params:GetNoteDto):Observable<PagedData<PreNoteDto>> {
    const url = blogApiUrl.getNoteList;
    return this.abpGet<PagedData<PreNoteDto>>(url,params);
  }

  public GetNote(id:number):Observable<PreNoteDto>{
    const url = blogApiUrl.getNoteList+"?Id="+id;
    return this.abpGet<PreNoteDto>(url);
  }

  public Like(id:number):void{
    const url = blogApiUrl.getNoteList;
    this.abpPost(url,null,{id:id})
  }
}
export class GetNoteDto{
  SkipCount = 0;
  MaxResultCount = 10;
  key = '';
}
export class PreNoteDto{
  id:number;
  title:string;
  creationTime:string;
  like:number;
  collect:number;
  scan:number;
  isPublic:boolean;
  content:string;
}
// 分页数据类
export class PagedData<T>{
  items:T[];
  totalCount:number;
}

blog.module.ts中声明

import {BlogService} from "./blog.service";


  providers:    [ BlogService ],

博客模块列表组件

我打算这样实现列表,上面一个大的搜索框,下面就是列表,不用分页,使用加载更多的方式。
注意这个子模块我们要使用NG ZORRO,所以还是要在子模块中引入。后面这些和样式调整就不再写详细的内容了

布局note-list.component.html

<div class="content">
  <div class="serch-content">
    <nz-input [nzType]="'search'"  [(ngModel)]="key" [nzPlaceHolder]="'输入你想知道的'" style="height: 38px;"></nz-input>
  </div>
  <div>
    <div *ngFor="let note of preNoteList" class="note-list">
      <div class="note-title">
        <h1> <a (click)="linkTo(note.id)">{{note.title}}</a> </h1>
        <em>{{note.creationTime}}</em>
      </div>
      <article  [innerHTML]="note.content"></article>
      <div class="note-btn">
        <div>
          <i class="anticon anticon-eye"></i>{{note.scan}}
          <i class="anticon anticon-heart"></i> {{note.like}}
        </div>
      </div>
    </div>
  </div>
  <div *ngIf="loadMore" class="load-more" (click)="getNoteList()" >
    <span>点击加载更多</span><i class="anticon anticon-arrow-down"></i>
  </div>
  <div *ngIf="loading" class="load-more">
    <nz-spin></nz-spin>
  </div>
</div>


note-list.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import marked from 'marked';
import {BlogService, PreNoteDto,GetNoteDto} from "../blog.service"

@Component({
  selector: 'app-note-list',
  templateUrl: './note-list.component.html',
  styleUrls: ['./note-list.component.css']
})
export class NoteListComponent implements OnInit {
  preNoteList:PreNoteDto[]=[];
  loadMore = false;
  loading =false;
  key="";

  constructor(private router: Router,
  private blogService :BlogService
  ) { }

  ngOnInit() {
    this.getNoteList();
  }
  getNoteList(f=false){
    this.loading= true;
    if(f)this.preNoteList =[];
    const param = new GetNoteDto();
    param.key = this.key;
    param.SkipCount = this.preNoteList.length;
    this.blogService.GetNoteList(param).do(()=>{
      this.loading = false;
    }).subscribe(m=> {
      this.loadMore = m.totalCount>this.preNoteList.length;
      m.items.forEach((v,i)=>{
        v.content = marked(v.content);
        this.preNoteList.push(v);
      });
    });
  }
  linkTo(id:number){
    this.router.navigate(['blog/note', id]);
  }

}


image.png

博客文章显示

布局 note.component.html

<div class="content">
  <div class="note-title">
    <h1> {{note.title}} </h1>
    <div class="note-btn">
      <div>
        <em>{{note.creationTime}}</em>
        <i class="anticon anticon-eye"></i>{{note.scan}}
        <i class="anticon anticon-heart"></i> {{note.like}}
      </div>
    </div>
  </div>
  <article  [innerHTML]="note.content"></article>
  <div *ngIf="loading" class="load">
    <nz-spin></nz-spin>
  </div>
  <div style="margin: auto;padding: 50px 10px;">
    <div class="like" [ngClass]="{'liked':_like}" (click)="ILike()">
      <i class="anticon anticon-heart-o"></i>喜欢 | {{note.like}}
    </div>
  </div>
</div>

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'; // 路由
import {BlogService, PreNoteDto} from "../blog.service"
import marked from 'marked';

@Component({
  selector: 'app-note',
  templateUrl: './note.component.html',
  styleUrls: ['./note.component.css']
})
export class NoteComponent implements OnInit {

  _like=false;
  note= new PreNoteDto();
  loading=true;
  constructor(private route: ActivatedRoute,
              private server:BlogService
              ) { }

  ngOnInit() {
    // 获取路由传值
    this.route.params.subscribe((params) => {
      const id = params.id;
      this.server.GetNote(id).subscribe(r=>{
        r.content = marked(r.content);
        this.note = r;
      },r=>{
        console.error(r);
        },
        ()=>{
        this.loading= false;
        })
    });
  }
  ILike(){
    this._like = !this._like;
    if(this._like){
      this.note.like++;
      this.server.Like(this.note.id);
    }else {
      this.note.like--;
      this.server.UnLike(this.note.id);
    }
  }

}

image.png

先简单实现,后面再慢慢优化吧

简单实现

添加点动画效果

定义两组动画:入场浮动动画,点击喜欢时的动画效果

在share文件夹下添加一个动画效果文件animations.ts。

import {trigger, animate, style, group, animateChild, query, stagger, transition} from '@angular/animations';
//入场浮动效果
export const Float = trigger('Float', [
  transition(':enter', [
    style({ opacity: 0.5,transform: 'translate3d(-10px,10px,0)'}),
    animate(500)
  ])
]);

export const Bubble = trigger('Bubble', [
  transition('*=>Bubble', [
    animate(500, style({ opacity: 0,transform: 'scale(1.5)'}))
  ]),
  transition('*=>UnBubble', [
    animate(500, style({ opacity: 0,transform: 'scale(0.5)'}))
  ])
]);

在note-list使用中使用
html

<div *ngFor="let note of preNoteList" class="note-list" [@Float]="">

ts

import {Float} from "../../../share/animations"

@Component({
  selector: 'app-note-list',
  templateUrl: './note-list.component.html',
  styleUrls: ['./note-list.component.css'],
  animations: [ Float ]
})


在note中使用
html

<div class="like" [ngClass]="{'liked':_like}" (click)="ILike()" [@Bubble]="State">

ts

import {Float,Bubble} from "../../../share/animations"
@Component({
  selector: 'app-note',
  templateUrl: './note.component.html',
  styleUrls: ['./note.component.css'],
  animations: [ Float,Bubble ]
})


  State="";

  ILike(){
    this._like = !this._like;
    if(this._like){
      this.note.like++;
      this.State="Bubble";
      this.server.Like(this.note.id);
    }else {
      this.note.like--;
      this.State="UnBubble";
      this.server.UnLike(this.note.id);
    }
  }
加入动画效果

有动画使用相关疑惑的可以参考我的这篇文章及其相关文章:Angular练习之animations动画

源码下载

思考

angular模块,组件,普通的ts文件之间的关系和区别。
动态路由是如何传值的
页面样式和布局如何优化

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,848评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,529评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,824评论 0 327
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,329评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,227评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,879评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,218评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,877评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,159评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,155评论 2 315
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,987评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,736评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,273评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,407评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,663评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,158评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,517评论 2 339

推荐阅读更多精彩内容