angularjs4+(12)已有项目中配置路由

1 参考上节新建app-routing.module.ts路由文件

2 在 app.module.ts 引入刚才定义的路由

import { AppRoutingModule } from './app-routing.module';

3 在app.module.ts 里面的 import 注册这个路由模块

imports: [
 BrowserModule,
 AppRoutingModule
 ]

4 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由

<router-outlet></router-outlet>

angularjs4+(11)父子路由

1 创建组件addnews

ng g component zujian/addnews

2 我想让http://localhost:4200/news/add能访问到news的子路由addnews,路由配置app-routing.module.ts如下:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {HomeComponent} from './zujian/home/home.component';
import {NewsComponent} from './zujian/news/news.component';
import {NewscontentComponent} from './zujian/newscontent/newscontent.component';
import { AddnewsComponent } from './zujian/addnews/addnews.component';//引入组件
const routes: Routes = [
  {path: 'home', component: HomeComponent},
  {path: 'news', component: NewsComponent,
//配置子路由
    children:[{
      path:'add',
      component:AddnewsComponent
      }]

},
  {path: 'newscontent/:id', component: NewscontentComponent},
  {
      path: '**',/*匹配不到的任意的路由*/
      redirectTo: '/home',
      pathMatch: 'full'
    } 
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

3 news.component.html加上:

<router-outlet></router-outlet>

angularjs4+(10)动态路由配置及传值

1 接上一节,还记得有个

{path: ‘newscontent/:id’, component: NewscontentComponent},
那么,newscontent组件如何获取路由传递过来的id呢,上代码(newscontent.component.ts):

import { Component, OnInit } from '@angular/core';
import {Router,ActivatedRoute,NavigationExtras} from '@angular/router';
@Component({
  selector: 'app-newscontent',
  templateUrl: './newscontent.component.html',
  styleUrls: ['./newscontent.component.css']
})
export class NewscontentComponent implements OnInit {

  constructor(private route:ActivatedRoute,private router:Router) { }

  ngOnInit() {
    //获取总路由传过来的id值
    console.log(this.route.params);

  }

  goNews(){
    // 不带参数从newscontent组件跳转到news组件
    this.router.navigate(['/news']);
  }

  goNewsWithParam()
  {
    //get传参
    let navigationExtras:NavigationExtras = {
      queryParams:{
        'sid':'123'
      },
      fragment:'anchor'
    };

    this.router.navigate(['/news'],navigationExtras);
    }


}

2 带参数从newscontent组件跳转到news组件后,news组件怎么接收参数呢,上代码news.component.ts:

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';

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


  constructor(private route: ActivatedRoute) {
    console.log(this.route.queryParams);
    }
  ngOnInit() {
  }

}

3 总结:ActivatedRoute组件用来接收参数,Router组件用来跳转

angularjs4+(9)路由配置

1 生成带路由的项目

ng new demo –routing

2 创建组件

ng g component zujian/home
ng g component zujian/news
ng g component zujian/newscontent

3 在路由文件app-routing.module.ts里引入组件,写路由规则

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {HomeComponent} from './zujian/home/home.component';
import {NewsComponent} from './zujian/news/news.component';
import {NewscontentComponent} from './zujian/newscontent/newscontent.component';

const routes: Routes = [
  {path: 'home', component: HomeComponent},
  {path: 'news', component: NewsComponent},
  {path: 'newscontent/:id', component: NewscontentComponent},
  {
      path: '**',/*匹配不到的任意的路由*/
      redirectTo: '/home',
      pathMatch: 'full'
    } 
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

4 app.component.html

<h1>
  <a routerLink='/home' routerLinkActive="active">home</a>
  <br>
  <a routerLink='/news' routerLinkActive="active">news</a>
</h1>

<router-outlet></router-outlet>

routerLinkActive用来设置选中路由的状态
app.component.css

.active{
    color:red;
   }

angularjs4+(8)父组件调用子组件定义的方法

1.father.component.html:

<app-son #son></app-son>
<hr>
<button (click)='son.haha()'>调用son里的haha方法</button>

2.son.component.ts定义haha函数

haha(){
    console.log("this is son func");
  }

以上是在父html里面调用子组件的方法,那怎么在父ts里调用子组件的方法呢?继续阅读

3 father.component.ts引入 ViewChild,并和父html里面的子组件关联起来

import { Component, OnInit,ViewChild} from '@angular/core';

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

  @ViewChild('son') son;
  constructor() { }

  ngOnInit() {
    this.son.haha();
  }
}

angularjs4+(7)子组件传值给父组件

1. 子组件引入 Output 和 EventEmitter;子组件中实例化 EventEmitter;子组件通过 EventEmitter 对象 outer 实例广播数据

import { Component,Input,Output,EventEmitter} from '@angular/core';

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

  @Output() private outer=new EventEmitter<string>();
  constructor() { }

  sendParent(){
    this.outer.emit('msg from child')
  }

  ngOnInit() {
    this.sendParent();
  }
}

2 父组件调用子组件的时候,定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer

<app-son (outer)="runParent($event)"></app-son>>

3 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据

import { Component, OnInit } from '@angular/core';

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

  public msg2;
  constructor() { }

  ngOnInit() {
    this.msg2 = "test";
  }

  runParent(msg:string){
    this.msg2 = msg;
  }

}

angularjs4+(6)父组件传值给子组件

1. 新建父组件father,子组件son

ng g component father
ng g component son

2.父组件father.component.ts里面定义变量msg和方法run:

import { Component, OnInit } from '@angular/core';

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

  public msg="test";
  constructor() { }

  ngOnInit() {
  }

  run(){
    this.msg = "this is from father";
  }

}

3. 父组件father.component.html里面引用son,给son传递msg和run

<app-son [msg]="msg" [run]="run"> </app-son>

4. son.component.ts里引入Input用来接收father的变量和方法:

import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-son',
  templateUrl: './son.component.html',
  styleUrls: ['./son.component.css']
})
export class SonComponent implements OnInit {
  @Input() msg:string;
  @Input() run:any;
  constructor() { }

  ngOnInit() {
    this.run();
    console.log(this.msg);
  }

}

子组件就可以像调用自己定义的变量和方法一样调用父组件定义的变量和方法

angularjs4+(5)关于rxjs

1.在需要使用rxjs的页面引入

import {Observable} from "rxjs";
import 'rxjs/Rx';
//npm install rxjs-compat //版本兼容可以执行这个命令

2.ts代码如下:

import { Component, OnInit } from '@angular/core';
import {Http,Jsonp} from "@angular/http";

//使用rxjs
import {Observable} from "rxjs";
import 'rxjs/Rx';
//npm install rxjs-compat //版本兼容

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
list=[];
  constructor(private http:Http,private jsonp:Jsonp) { }

  ngOnInit() {
  }

   rxjsMsg(){

    var _that = this;
     // alert('请求数据');
      var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK";
      this.jsonp.get(url).map(res=>res.json())  /*返回的数据转换成json*/
      .subscribe(function(data){

          console.log(data);
          _that.list = data.result;

      },function(err){

          console.log(err);
      })
  }

}

2.html代码如下,和上一节共用:

<h2>
  home works!ttt
</h2>
<br>
<button (click)="getMsg()">getmsg</button>
<br>
<hr>
<button (click)="jsonpMsg()">jsonpMsg</button>
<hr><br>
<hr>
<button (click)="postMsg()">postMsg</button>
<hr><br>

<button (click)="rxjsMsg()">rxjsMsg</button>
<hr><br>


<ul>
  <li *ngFor="let item of list">
    {{item.title}}
  </li>
</ul>

angularjs4+(4)请求数据

1. http访问请求json数据

请求json数据格式如下:

{
    "result": [
        {
            "aid": "501",
            "catid": "8",
            "username": "admin",
            "title": "nodejs【全栈】【人工智能】 视频教程下载",
            "pic": ""
        },
        {
            "aid": "489",
            "catid": "8",
            "username": "admin",
            "title": "cordova常用命令大全/phonegap命令大全",
            "pic": ""
        },
        {
            "aid": "328",
            "catid": "8",
            "username": "admin",
            "title": "phonegap桌面开发工具视频教程-不搭建环境就可以开发phonegap app ...",
            "pic": "portal/201501/11/200317ne0ki707lkinl69e.png"
        },
        {
            "aid": "36",
            "catid": "8",
            "username": "admin",
            "title": "HTML5 Canvas  制作一个“在线画板” 视频教程(第六讲)",
            "pic": "portal/201307/24/214740o6em58som6i60e90.png"
        }
    ]
}

2. app.module.ts引入 HttpModule 、JsonpModule

    import { HttpModule, JsonpModule } from '@angular/http';
...
imports: [
 BrowserModule,
 FormsModule,
 HttpModule,
 JsonpModule,
 AppRoutingModule
 ],

3. 在需要请求数据的地方引入 Http,Jsonp

import {Http,Jsonp} from "@angular/http";

4. 构造函数内申明:

constructor(private http:Http,private jsonp:Jsonp) { }

5.get和jsonp请求的写法:

 getMsg(){
    var _that = this;
    this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1")
 .subscribe(
 function(data){
 //需要自己解析数据
   _that.list=JSON.parse(data['_body']).result;
 },function(err){
 console.log('失败');
 }
 );
  }

  jsonpMsg(){
    var _that = this;
   //注意拼接callback=JSONP_CALLBACK this.jsonp.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK")
 .subscribe(
 function(data){
   console.log(data);
   //跨域返回json格式数据,不需要解析
   _that.list=data['_body']['result'];
 },function(err){
 console.log('失败');
 }
 );
  }

6.post请求数据写法,注意三个参数

  postMsg(){
    var _that = this;
    this.http.post("http://baidu.com",JSON.stringify({username: 'admin'}), {headers:this.headers})
 .subscribe(
 function(data){
   console.log(data.json());
  // _that.list=JSON.parse(data['_body']).result;
 },function(err){
 console.log('失败');
 }
 );
  }

angularjs4+(3.services)

service即一堆component的集合

1. 创建服务命令

创建到指定目录下面
ng g service services/storage

2.app.module.ts 里面引入创建的服务

import { StorageService } from './services/storage.service';
NgModule 里面的 providers 里面依赖注入服务
providers: [StorageService],

3.使用的页面引入服务,注册服务

“`javascript
import { StorageService } from '../../services/storage.service';
constructor(private storage: StorageService) {}

<pre class="line-numbers prism-highlight" data-start="1"><code class="language-null"># 4.ts里面加入缓存逻辑
“`javascript
export class TodolistComponent implements OnInit {
list=[];
thing=””;
constructor(private storage:StorageService) { }

ngOnInit() {
if(this.storage.get(‘tdlist’)){
this.list = this.storage.get(‘tdlist’);
}
}

add(){
var obj={“name”:this.thing,”status”:0};
this.list.push(obj);
this.thing=””;
this.storage.set(‘tdlist’,this.list);
}

del(key){
this.list.splice(key,1);
this.storage.set(‘tdlist’,this.list);
}

change(key,status){
this.list[key].status=status;
this.storage.set(‘tdlist’,this.list);
}

}
“`

# 5 实现storage服务
“`javascript
export class StorageService {

constructor() { }

set(key,value){
localStorage.setItem(key,JSON.stringify(value));
}

get(key){
return JSON.parse(localStorage.getItem(key));
}

remove(key){
localStorage.removeItem(key);
}
}