• angular4-http


    导入 Http 模块

    import { HttpModule } from '@angular/http';
    
    @NgModule({
      imports: [BrowserModule, FormsModule, HttpModule],
      declarations: [AppComponent, UserComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    import { Component, OnInit } from '@angular/core';
    import { Http } from '@angular/http'; // (1)
    import 'rxjs/add/operator/map'; // (2)
    
    interface Member {
        id: string;
        login: string;
        avatar_url: string;
    }
    
    @Component({
        selector: 'sl-members',
        template: `
        <h3>Angular Orgs Members</h3>
        <ul *ngIf="members">
          <li *ngFor="let member of members;">
            <p>
              <img [src]="member.avatar_url" width="48" height="48"/>
              ID:<span>{{member.id}}</span>
              Name: <span>{{member.login}}</span>
            </p>
          </li>
        </ul>
        `
    })
    export class MembersComponent implements OnInit {
      members: Member[];
    
      constructor(private http: Http) { } // (3)使用 DI 方式注入 http 服务
    
      ngOnInit() {
        this.http.get(`https://api.github.com/orgs/angular/members?page=1&per_page=5`) // (4)调用 http 服务的 get() 方法,设置请求地址并发送 HTTP 请求
            .map(res => res.json()) // (5)调用 Response 对象的 json() 方法,把响应体转成 JSON 对象
            .subscribe(data => {
               if (data) this.members = data; // (6)把请求的结果,赋值给对应的属性
            });
        }
    }

    声明 MembersComponent 组件

    import { MembersComponent } from './members.component';
    
    @NgModule({
      imports: [BrowserModule, FormsModule, HttpModule],
      declarations: [AppComponent, UserComponent, MembersComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

    使用 MembersComponent 组件

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <sl-members></sl-members>
      `,
    })
    export class AppComponent {}
  • 相关阅读:
    java中bean和xml相互转换
    java操作zip文件
    java内置的解压缩工具
    java操作Excel简单入门
    java开发IDEA插件入门
    java中Class.getResourceAsStream()和ClassLoader.getResourceAsStream()的区别
    java中文转拼音
    vue父子组件通信
    学会使用box-sizing布局
    webpack-dev-server 导致的 invalid host header
  • 原文地址:https://www.cnblogs.com/avidya/p/7464808.html
Copyright © 2020-2023  润新知