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

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');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件间通信 父组件与子组件通信: props down 子组件与父组件通信:events up 若父组件要想获取子...
    JSL_FS阅读 514评论 0 0
  • Vue组件是Vue的一个重要组成部分,所以掌握Vue组件间的通信是十分重要的,一共分三种情况:父组件向子组件传值、...
    Darsoon阅读 174评论 0 0
  • 组件的构成 组件意味着协同工作,通常父子组件会是这样的关系:组件 A 在它的模版中使用了组件 B 。它们之间必然需...
    webHyman阅读 534评论 0 1
  • 上午,校长带领全校班主任倾巢出动,去兄弟单位取经学习,为了下个月的迎检做准备,每个学校都有闪光点,都有我们学习的地...
    青荷妖妖阅读 773评论 4 3
  • 店里来了个新员工, 有点土,但很听话 其它店员都把所有得工作堆给他做, 新店员不介意… 默默地帮她们都完成, 店长...
    张宝雷阅读 743评论 0 1