angular2--http

1、在app目录下面创建一个json文件,用于http请求。

[{"id":11,"name":"苹果"},{"id":12,"name":"三星"},{"id":13,"name":"乐视"},{"id":14,"name":"华为"}]

2、然后我们需要写一个json对应的对象类型的组件mobile.ts,便于解析。

import {Injectable} from 'angular2/core';

export class Mobile {
    constructor(public id: number, public name: string) { }
}

3、在主组件AppComponent 中写Http的请求。

import {Component} from 'angular2/core';
import {Http} from 'angular2/http';

import 'rxjs/add/operator/map';
import {Mobile} from './mobile'
@Component({
    selector: 'my-app',
    template: `
    <h1>Angular 2 App</h1>
    <ul *ngIf="mobiles">
           <li *ngFor="#m of mobiles"><span>{{m.id}}</span> {{m.name}}</li>
    </ul>

    `

})
export class AppComponent implements OnInit { 
    public mobiles: Mobile[];
    constructor(public http: Http) {
        console.log(" AppComponent constructor :", "run step constructor ");

        http.get('app/mobile.json').subscribe(res=> this.mobiles =res.json());

    }    
    ngOnInit() {
        console.log(" AppComponent ngOnInit :", "run step ngOnInit ");

    }
}

总结:上面关键是通过 http组件调用get方法 来加载本地的json文件。对于上面的代码http.get('app/mobile.json').map(res => res.json()).subscribe(v=> this.mobiles = v); 不是很清楚map方法和subscribe方法到底做了什么。从名字上是先进行返回结果map解析,然后再转为Mobile对象数组。

4、在index.html中我们需要添加http.js文件,从最近的学习看 我发现所有的组件最后都转为js文件,所以Angular中运行的是js文件,包括我们写的Mobile组件等等。 index.html的内容如下:

<html>

  <head>
    <title>Angular 2 QuickStart</title>

    <!-- 1. Load libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/http.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>

</html>

提示 引入http.js的路径:node_modules/angular2/bundles/http.js

在刚开始的时候,在angular2目录我首先发现了这里有一个http.js 结果引入的是:node_modules/angular2/http.js 然后始终不能正常运行,搞了好半天才知道引入错误了。

5、

HTTP访问后端URL

如果要访问后端的资源,比如后端的资源是http://localhost:8080/mobile.json

修改一下上面的Http请求

http.get('http://localhost:8080/mobile.json').map(res => res.json()).subscribe(v=> this.mobiles = v);

解决跨域
  1. 服务器端设置可以进行跨域资源的访问。

2.通过Nginx配置一个 统一Angular APP和服务器端的域名,反代到前端和后端。

原文地址:https://www.cnblogs.com/zhangjinting/p/6666567.html