Angular2学习
1.新建项目

2.新建Model
public class TodoItem
{
public int Id { get; set; }
public string Key { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
public string Desc { get; set; }
}
3.数据访问接口
public interface ITodoRepository
{
IEnumerable<TodoItem> GetAll();
void Add(TodoItem item);
TodoItem Find(string key);
TodoItem Remove(string key);
void Update(TodoItem item);
}
4.接口实现
public class TodoRepository : ITodoRepository
{
//fake datasource
static ConcurrentDictionary<string, TodoItem> _todos = new ConcurrentDictionary<string, TodoItem>(); //constructor
public TodoRepository()
{
TodoItem item = new TodoItem()
{
Id=1,
Key = Guid.NewGuid().ToString(),
Name = "first todo item",
IsComplete = false,
Desc="desc content from first todo"
}; _todos.TryAdd(item.Key, item);
} //get all items
public IEnumerable<TodoItem> GetAll()
{
return _todos.Values;
} //add new item
public void Add(TodoItem item)
{
item.Id = 1;
item.Key = Guid.NewGuid().ToString();
item.Name = Guid.NewGuid().ToString().Split('-')[0].ToUpper(); _todos[item.Key] = item;
} //find the item by key
public TodoItem Find(string key)
{
TodoItem item;
_todos.TryGetValue(key, out item);
return item;
} //remove the item by key
public TodoItem Remove(string key)
{
TodoItem item;
_todos.TryGetValue(key, out item);
_todos.TryRemove(key, out item);
return item;
} //update the item by key
public void Update(TodoItem item)
{
_todos[item.Key] = item;
}
}
5.api
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using ToDoApi.Models; namespace ToDoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController:Controller
{
public ITodoRepository _TodoRepository { get; set; } public TodoController(ITodoRepository todoRepository)
{
_TodoRepository = todoRepository;
} //get:api/todo
public IEnumerable<TodoItem> GetAll()
{
return _TodoRepository.GetAll();
} //get:api/todo/id
[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
var item = _TodoRepository.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
} //put: api/todo
[HttpPost]
//[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
public IActionResult Create(TodoItem item)
{
if (item == null)
{
return BadRequest();
} _TodoRepository.Add(item);
return CreatedAtRoute("GetTodo", new { controller = "Todo", id = item.Key }, item);
} //Update
[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody] TodoItem item)
{
if (item == null || item.Key != id)
{
return BadRequest();
} var todo = _TodoRepository.Find(id);
if (todo == null)
{
return NotFound();
} _TodoRepository.Update(item);
return new NoContentResult();
} //delete:api/todo/id
[HttpDelete("{id}")]
public void Delete(string id)
{
_TodoRepository.Remove(id);
} }
}
6.Gulp文件
var gulp = require('gulp'),
path = require("path"),
livereload = require('gulp-livereload'),
connect = require('gulp-connect'),
open = require('open'),
watch=require('gulp-watch'),
port=9000;
var PATHS = {
src: 'app/**/*.ts',
typings: 'node_modules/angular2/bundles/typings/**/*.d.ts',
libs: [
"node_modules/angular2/bundles/angular2.dev.js",
"node_modules/angular2/bundles/angular2-polyfills.js",
"node_modules/angular2/bundles/router.dev.js",
"node_modules/angular2/bundles/http.dev.js",
"node_modules/systemjs/dist/system.src.js",
"node_modules/rxjs/bundles/Rx.js"
],
html: 'app/**/*.html',
dist: "dist"
};
gulp.task('clean', function (done) {
var del = require('del');
del(['dist'], done);
});
gulp.task("libs", function(){
gulp.src(PATHS.libs).pipe(gulp.dest(PATHS.dist + "/libs"));
})
gulp.task("html", function(){
gulp.src(PATHS.html).pipe(gulp.dest(PATHS.dist));
// .pipe(watch())
//.pipe(connect.reload());
})
gulp.task('ts2js', function () {
var typescript = require('gulp-typescript');
var tsResult = gulp.src([PATHS.src, PATHS.typings])
.pipe(typescript({
noImplicitAny: true,
module: 'system',
target: 'ES5',
emitDecoratorMetadata: true,
experimentalDecorators: true
}));
return tsResult.js.pipe(gulp.dest(PATHS.dist));
});
gulp.task('play', ['html', 'libs', 'ts2js'], function () {
var http = require('http');
var _connect = require('connect');
var serveStatic = require('serve-static');
gulp.watch(PATHS.src, ['ts2js']);
gulp.watch(PATHS.html, ['html']);
var app = _connect().use( serveStatic(path.join(__dirname, PATHS.dist)) );
http.createServer(app).listen(port, function () {
open('http://localhost:' + port);
});
});
// 自动刷新不可用
gulp.task('server',['html', 'libs', 'ts2js'],function(){
gulp.watch(PATHS.src, ['ts2js']);
gulp.watch(PATHS.html, ['html']);
open('http://192.168.2.120:' + port);
connect.server({
port: port,
root:PATHS.dist,
livereload: true
});
})
7.People模块为例, people-service.ts
import { Injectable } from "angular2/core";
import { Http,Response,Headers,RequestOptions } from 'angular2/http';
@Injectable()
export class PeopleService{
names:Array<string>;
url:string="http://localhost:10003/api/todo/";
constructor(private _http:Http){
// //fade initialize
// this.names=[
// {Id:100,Key:"",Name:"Lisa",IsComplete:false,Desc:"homeless can you here me."},
// {Id:101,Key:"",Name:"Miskovsky",IsComplete:false,Desc:"calling back little bird."},
// {Id:102,Key:"",Name:"Jennifer",IsComplete:false,Desc:"Seattle is sunshine now."},
// {Id:103,Key:"",Name:"Lana Del Ray",IsComplete:false,Desc:"<<Summertime Sadness>>"},
// {Id:104,Key:"",Name:"Aili",IsComplete:false,Desc:"weibo english"},
// {Id:105,Key:"",Name:"July",IsComplete:false,Desc:"come with back love"},
// {Id:106,Key:"",Name:"Rlogue",IsComplete:false,Desc:"fall with you"}
// ];
}
//get from local
getPeopleList(){
console.log("get date from server !");
return this.names;
}
//get info from local
getPersonDetail(id:number){
return this.names.find(function(p){
return p.Id==id;
});
}
//get data from webapi
getPeople(){
return this._http.get(this.url);
// .map(res=>res.json.data)
// .catch(function(error:Response){ console.log(error); });
}
//get info from webapi
getPerson(key:string){
return this._http.get(this.url+key);
}
addPerson(){
let body = JSON.stringify({
Id: 2,
"Key": "dba980a7-555b-44b8-9043-91fc22adc00b",
Name: "first todo item",
"IsComplete": false,
Desc: "desc content from first todo"
});
let headers = new Headers({'Content-type': 'application/json;'});
let options = new RequestOptions({ headers: headers });
console.log(body);
console.log(headers);
console.log(options);
return this._http.post(this.url, body, options).subscribe(resp=>console.info(resp););
}
};
8.people列表模块 people.ts
import { Component } from "angular2/core";
import { bootstrap } from "angular2/platform/browser";
import { HTTP_PROVIDERS } from "angular2/http";
import { PeopleService } from "people/people-service.js";
import { ROUTER_PROVIDERS,RouteParams,Router} from "angular2/router";
import { InfiniteScroll } from "components/infinite-scroll/infinite-scroll.js";
@Component({
selector:"app-people",
providers:[HTTP_PROVIDERS,PeopleService,Location],
templateUrl:"people/people.html",
// template:"<h1>PEOPLE</h1>",
directives:[InfiniteScroll],
styles:[`button {border: 1px solid Red;}`]
})
export class _People implements OnInit{
name:string;
age:number;
names:Array<string>;
isBusy:boolean=false;
constructor(private _people_service:PeopleService,private _router:Router){
this.name="Lisa Miskovsky";
this.age=27;
//Observable
_people_service.getPeople().subscribe(resp=>this.names=resp.json());
}
SayHello(private _name:string){
this.name=_name;
console.log("Hello IM:"+_name);
}
viewInfo(private _id:number){
this._router.navigate( ["Person", { id:_id }] );
}
onScroll(){
console.log("scrolled :"+new Date().getTime());
if(this.isBusy) return;
this.isBusy=true;
console.log("busy:"+this.isBusy);
// this.names=this.names.concat(this._people_service.getPeopleList());
this._people_service.getPeople().subscribe(resp=>this.names=this.names.concat(resp.json());
this.isBusy=false;
console.log("busy:"+this.isBusy);
console.log("load more over !");
}
}
export function render_people(){
bootstrap(_People, [ROUTER_PROVIDERS]).catch(err=>console.log(err));
}
9.people模块的页面展现(模拟滚动加载)
<section style="margin-top: 20px;"> <div infinite-scroll style="height:500px;overflow-y: scroll;"
[infiniteScrollDistance]="1"
[infiniteScrollThrottle]="500"
(scrolled)="onScroll()"
[scrollWindow]="false"> <div *ngFor="#person of names;#_index=index">
<p *ngIf="person" style="height:auto;border:1px solid #000;padding:5px;">
{{_index+1}}、{{person.Id}}-{{person.Name}} <br/>
<span>{{person.Key}}</span><br/>
<span>{{person.Desc}}</span><br/>
<button (click)="SayHello(person.Name)">SayHello</button>
<button (click)="viewInfo(person.Key)">ViewInfo</button>
</p>
</div> </div> </section>
11.源码
http://git.oschina.net/gaojinbogit/ng2-demo
12.angualr2 typescript学习资料
--ng2.0
文件上传api http://valor-software.com/ng2-file-upload/
系列博客 http://www.cnblogs.com/1wen/p/5446863.html
快速上手 http://cnodejs.org/topic/55af2bc4911fb957520eacef
推酷站点 http://www.tuicool.com/articles/mi6rmuB
中文社区 http://www.angularjs.cn/A2pG
语法清单 https://segmentfault.com/a/1190000004071388
深度开源 http://www.open-open.com/lib/list/396
一些资料 https://segmentfault.com/a/1190000003761054
大量资料 https://github.com/timjacobi/angular2-education
1.x升级2 http://www.wtoutiao.com/p/C34jXG.html
--typescript
ES6简介 http://es6.ruanyifeng.com/#docs/intro
博客 http://www.cnblogs.com/smartkid/archive/2012/10/05/A_First_Look_Of_TypeScript.html
系列教程 http://www.cnblogs.com/tansm/p/TypeScript_Handbook_Enums.html
GitBook https://www.gitbook.com/book/zhongsp/typescript-handbook/details
tsc转职 http://www.cnblogs.com/crazylights/p/5234884.html
Angular2学习的更多相关文章
- Angular2学习笔记(1)
Angular2学习笔记(1) 1. 写在前面 之前基于Electron写过一个Markdown编辑器.就其功能而言,主要功能已经实现,一些小的不影响使用的功能由于时间关系还没有完成:但就代码而言,之 ...
- angular2学习--根模块
最近有时间,学习一下angular2,根据自己的理解添加一些自己的理解,有什么不对的地方请指教, 学习的地址是https://angular.cn/ 下边是分享一下我学习过程 angular2和ang ...
- Angular2学习笔记(1)——Hello World
1. 写在前面 之前基于Electron写过一个Markdown编辑器.就其功能而言,主要功能已经实现,一些小的不影响使用的功能由于时间关系还没有完成:但就代码而言,之前主要使用的是jQuery,由于 ...
- angular2框架搭建,angular-cli使用,angular2学习
angular红红火火很多年了,一眨眼ng4都出来了,我也只能叹息前端的日新月异,以及感叹自己永远追赶不上时代的步伐,但是没关系,一个优秀的前端不在于他懂的无数的框架,而在于遇到问题时候懂得如何学习, ...
- angular2学习资源汇总
文档博客书籍类 官方网站: https://angular.io 中文站点: https://angular.cn Victor的blog(Victor是Angular路由模块的作者): https: ...
- Angular2学习笔记——路由器模型(Router)
Angular2以组件化的视角来看待web应用,使用Angular2开发的web应用,就是一棵组件树.组件大致分为两类:一类是如list.table这种通放之四海而皆准的通用组件,一类是专为业务开发的 ...
- Angular2学习笔记——Observable
Reactive Extensions for Javascript 诞生于几年前,随着angular2正式版的发布,它将会被更多开发者所认知.RxJs提供的核心是Observable对象,它是一个使 ...
- Angular2学习笔记——在子组件中拿到路由参数
工作中碰到的问题,特此记录一下. Angular2中允许我们以`path\:id\childPath`的形式来定义路由,比如: export const appRoutes: RouterConfig ...
- Angular2学习笔记——NgModule
在Angular2中一个Module指的是使用@NgModule修饰的class.@NgModule利用一个元数据对象来告诉Angular如何去编译和运行代码.一个模块内部可以包含组件.指令.管道,并 ...
随机推荐
- 【转】jQuery教程
“jQuery风暴” 推荐及配套代码下载 ziqiu.zhang 2011-03-24 00:28 阅读:15339 评论:100 从零开始学习jQuery(剧场版) 你必须知道的javascri ...
- 微信小程序,大多数人误解的8个问题
作者:王安,数字天堂DCloud公司创始人兼CEO 注:本文内容包含技术.商业,不懂技术的读者可以只看商业相关的内容.本文仅代表作者一家之言,如有不同意见,欢迎留言讨论~ 8个误解 坊间所传的信息很多 ...
- 一个基于nodejs,支持http/https的中间人(MITM)代理,便于渗透测试和开发调试。
源码地址:https://github.com/wuchangming/node-mitmproxy node-mitmproxy node-mitmproxy是一个基于nodejs,支持http/h ...
- #module-django.db.models
Models A model is the single, definitive source of information about your data. It contains the esse ...
- 抽象数据类型Triplet的C语言实现
#include <stdio.h> #include <stdlib.h> #define ERROR 0 #define OK 1 typedef int Status; ...
- 使用c语言编写cgi程序
http://blog.chinaunix.net/uid-22566367-id-3109877.html 简单的说,cgi是沟通HTML表单和服务器端程序的接口,是可以被其他语言所应用的一个规范集 ...
- 最好用的手机编程软件-C4droid
Q:c4droid是什么? A:c4droid(以下简称c4)是安卓平台上最强大的c/c++ 编译器,你可以在手机上用手机编写自己的C/C++程序,并且可以把程序导出成apk文件. 下载地址:http ...
- sort 命令
sort sort -t': ' -k 2n -t 可以自定义分隔符 -k 可以自定义分割后取第几个字符串作为排序值 2n表示第二个值,并作为数字来排序
- HttpClient4.3.6 实现https访问
package httptest; import java.io.IOException; import java.nio.charset.Charset; import java.security. ...
- Jump
hdu4862:http://acm.hdu.edu.cn/showproblem.php?pid=4862 题意:给你n*m的方格,每个方格中有一个数(0---9),然后你每次可以选择一个点开始,这 ...