美文网首页我爱编程
Angular组件间通信,与服务器端通信

Angular组件间通信,与服务器端通信

作者: JSL_FS | 来源:发表于2018-02-08 09:14 被阅读0次

    props down

    //send
    <datou [myvalue]="treasure"></datou>
    //receive
    import {input} from '@angular/core'
    
    @input() myvalue="";
    
    this.myvalue
    

    events up

    //①biding receive
    //指定处理函数
    rcvmsg(msg){
    //绑定自定义事件的处理函数
    (customevent)="rcvmsg($event)"
    //②emit send
    import {output,eventemitter} from '@angular/core'
    @output() customevent = new eventemitter() 
    this.customevent.emit(123)
    

    服务的创建

    import {injectable} from '@angular/core'
    
    @injectable()
    export class myservice{
        checkuserlogin(){
           return true
        }
    }
    

    服务的使用(服务是为了处理应用程序的应用逻辑,服务就是封装经常用到的方法和数据,方便组件去复用)

    //1、指定providers
    provders:[myservice]
    //2、将服务进行实例化并调用
    import {myservice} from '***'
    constructor(private ms:myservice){}
    this.ms.checkuserlogin();
    

    网络请求的创建

    import {injectable} from '@angular/core'
    import {http,response} from '@angular/http'
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    
    @injectable()
    export class myhttpservice{
    
       constructor(private http:http){}
    
       sendrequest(myurl:string){
          //发起网络请求
          return this.http
              .get(myurl)
              .map((response:response)=>{
                 return  response.json();
              })
       }
    }
    

    网络请求的使用

    //以模块为例
    import {myhttpservice} from '***'
    @ngmodule({
      providers:[myhttpservice]
    })
    
    import {myhttpservice} from '***'
    constructor(private ms:myhttpservice){}
    this.ms.sendrequest('***')
    .subscribe((result:any)=>{
    
    })
    

    若网络请求涉及session

    //客户端
    this.http.get(
    myurl,
    {withcredenetials:true}
    )
    //php服务端
    header('access-control-allow-origin:http://localhost:3000');
    header('access-control-allow-credentials:true');
    

    相关文章

      网友评论

        本文标题:Angular组件间通信,与服务器端通信

        本文链接:https://www.haomeiwen.com/subject/quvzzxtx.html