zoukankan      html  css  js  c++  java
  • angular2 问题请教

    angular2 通过http服务进行对后端api的远程调用?

    我简单的尝试了一下,发现了几个问题,记录一下,以方便查找问题。

    1. angular2 http服务的跨域问题?跨域本身就是一个很复杂的问题,angular2对跨域的处理。
    2. angular2 如果在providers中加入http服务会出现什么问题?
    3. promise http服务会强迫我们使用Observerable,但是我们可以转换成promise,还是遵循官方指导,学习rxjs吧。

    现在我们先看第二个问题?

     1 import { NgModule } from '@angular/core';
     2 import { Http, HttpModule } from '@angular/http';
     3 import { HeroListComponent } from './hero-list.component';
     4 
     5 @NgModule({
     6     imports: [HttpModule],
     7     declarations: [HeroListComponent],
     8     providers: [Http]
     9 })
    10 
    11 export class HeroListModule
    12 { }

    我在providers中添加了http服务。如果此时我通过http获取远程url内容。

     1 import { Component } from '@angular/core';
     2 import { Http } from '@angular/http';
     3 
     4 @Component({
     5     templateUrl: './hero-list.component.html'
     6 })
     7 
     8 export class HeroListComponent {
     9     private baiduhtml: string;
    10     constructor(private http: Http) {
    11         this.http.get("http://localhost:8080/dashboard/datalist").toPromise().then((data) => {
    12             this.baiduhtml = data.text();
    13         }).catch(this.handleError);
    14     }
    15 
    16     private handleError(error: any): Promise<any> {
    17         console.error('An error occurred', error); // for demo purposes only
    18         return Promise.reject(error.message || error);
    19     }
    20 
    21 }

    很不好意思?出现了错误

    如果我们去掉providers中的http,执行正常。

    这是不是提示我们,服务不能重复的在providers中添加呢?那么如果不能重复添加,我们该如何避免呢?暂时没想到好办法,希望有合适方法的指导一下??

     因为团队开发,我们不能避免出现重复添加的问题。

    关于跨域问题的研究,加入一个header就可以搞定,这涉及到了http的细节,不属于问题。

  • 相关阅读:
    A Simple Problem with Integers poj 3468 多树状数组解决区间修改问题。
    Fliptile 开关问题 poj 3279
    Face The Right Way 一道不错的尺取法和标记法题目。 poj 3276
    Aggressive cows 二分不仅仅是查找
    Cable master(二分题 注意精度)
    B. Pasha and String
    Intervals poj 1201 差分约束系统
    UITextField的快速基本使用代码块
    将UIImage转换成圆形图片image
    color转成image对象
  • 原文地址:https://www.cnblogs.com/jiagoushi/p/6115954.html
Copyright © 2011-2022 走看看