2.http通讯

作者: Monee121 | 来源:发表于2018-03-08 20:21 被阅读0次

    学习内容:
    1.了解angular的Http服务
    2.发送http请求
    3.处理http响应
    https://segmentfault.com/a/1190000010116848 http和httpClient的区别
    异步的请求可以通过承诺,回调,响应式编程。默认用响应式编程。
    https://segmentfault.com/a/1190000010259536#articleHeader1 新的写法
    步骤1:ng g component product;
    我们需要在 AppModule 中导入 HttpClientModule 模块;
    第一种方法

    export class HttpComponent implements OnInit {
    
      dataSource: Observable<any>; /*接收响应返回的流*/
      products: Array<any> = [];  /*模板做数据绑定*/
      constructor(private http: HttpClient) {
        this.dataSource = this.http.get('http://www.rvhqs.cn/api/country');
      } /*本地的datasourse和get返回的流挂在一起*/
      ngOnInit(): void {
      this.dataSource.subscribe(
        (data) => this.products = data   /*订阅到的数据传给我的product*/
      );
      }
    } /*依赖注入*/
    
    同上:
    export class HttpComponent implements OnInit {
      products: Array<any> = [];  /*模板做数据绑定*/
      constructor(private http: HttpClient) {  } /*本地的datasourse和get返回的流挂在一起*/
      ngOnInit(): void {
        this.http.get('http://www.rvhqs.cn/api/country').subscribe(
          (data: Array<any>[]) => this.products = data   /*订阅到的数据传给我的product*/
        );
      }
    } /*依赖注入*/
    
    
    
    
    
    <p>
      商品信息
    </p>
    <ul>
      <li *ngFor="let product of products">
        {{product.name}}
      </li>
    </ul>
    
    

    异步:如果你不需要修改返回的数据直接使用 就可以用async

    export class HttpComponent implements OnInit {
    
      products: Observable<any>;
      constructor(private http: HttpClient) {
        this.products = this.http.get('http://www.rvhqs.cn/api/country');
      }
      ngOnInit(): void {
      }
    } /*依赖注入*/
    
    <p>
      商品信息
    </p>
    <ul>
      <li *ngFor="let product of products | async" >
        {{product.name}}
      </li>
    </ul>
    
    

    例子演示:发送请求带上请求头

    const headers = new HttpHeaders().set("X-CustomHeader", "custom header value");
    
    this.courses$ = this.http
        .get(
            "/courses.json",
            {headers})
        .do(console.log)
        .map(data => _.values(data));
    

    精确写法规范类型

    product.ts

    export class HttpComponent implements OnInit {
      results: Country[]; /*存返回的数据*/
      constructor(private http: HttpClient) {} /*依赖注入*/
    
      ngOnInit(): void {
        this.http.get('http://www.rvhqs.cn/api/country').subscribe((data: Country[]) => {
          this.results = data;
          console.log(this.results);
        });
      }
    }
    export interface Country {/*自定义类型*/
      id: number;
      name: string;
      name_native: string;
      minimum_age: number;
      default_unit: string;
      default_currency: number;
    }
    

    product.html

    <p>
      商品信息
    </p>
    <ul>
      <li *ngFor="let result of results">
        {{result.name}}
      </li>
    </ul>
    
    
    image.png

    相关文章

      网友评论

        本文标题:2.http通讯

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