简体   繁体   English

Angular 2 Http Request to Promise 返回 zone obj 而不是实际数据

[英]Angular 2 Http Request to Promise returns zone obj instead of actual data

I'm trying to have quick test of ng 2 http to return real data.我正在尝试快速测试 ng 2 http 以返回真实数据。 I know there is a better/longer way to do it.我知道有更好/更长的方法来做到这一点。 This is meant to be quick and simple, not best practices.这是为了快速和简单,而不是最佳实践。

I know the server returns data because I can see it in another terminal window.我知道服务器返回数据,因为我可以在另一个终端窗口中看到它。 The json is very simple {a:b} because it is just a proof of concept. json 非常简单 {a:b} 因为它只是一个概念证明。

I don't care if it is a promise or an observable as long as it hangs around to return the real data right there -- so I can figure out that it actually works -- not that I want to write production code that way.我不在乎它是 Promise 还是 observable,只要它一直在那里返回真实数据——所以我可以弄清楚它确实有效——而不是我想以这种方式编写生产代码。

//app.data.service.ts
import { Injectable }     from '@angular/core';
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';

@Injectable() export class DataService {
    constructor(private http: Http) { 
    }
    public getItems(){
       return this.http.get('http://localhost:8090/data/config.txt')
           .toPromise()
           .then(data => Promise.resolve(data.json()));
    }
}

// app.data.service.spec.ts
/* tslint:disable:no-unused-variable */
import { AppComponent } from './app.component';
import { TestBed, inject, fakeAsync } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { By } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { DataService } from './app.data.service';
describe('DataService', function () {
  let dataService: DataService;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      declarations: [AppComponent],
      providers: [DataService]
    });
    dataService = TestBed.get(DataService);
  });
  it('should be instantiated by the testbed', () => {
    expect(dataService).toBeDefined();
  });
  it('should return get', () => {
    let data = dataService.getItems();
    console.log('test data= ' + data);
    console.log('test string(data)= ' + JSON.stringify(data));
  });
});

//tail end of tests.html
      <tr class="system-out">
        <td colspan="3"><strong>System output:</strong><br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: 'WARNING: System.import could not load "systemjs.config.extras.js"; continuing without it.'
<br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: Error{originalErr: Error{}}
<br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: 'test data= [object Object]'
<br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: 'test string(data)= {"__zone_symbol__state":null,"__zone_symbol__value":[]}'
</td>

In app.data.service.ts在 app.data.service.ts

public getItems(){
   return this.http.get("http://......")
       .toPromise()
       .then(res => res.json())
       .catch(this.handleError);
}

In your component.ts call this method/subscribe to it在你的 component.ts 中调用这个方法/订阅它

  data:any;

  ngOnInit() {
    this.appService.getItems()
        .then(data => console.log(data));

  }

Several issues to fix this, debugging the chrome browser that the karma test popped up helped -解决这个问题的几个问题,调试 karma 测试弹出的 chrome 浏览器有帮助 -

  • server wasn't returning CORS headers服务器没有返回 CORS 标头
  • observable/subscribe code was not working可观察/订阅代码不起作用
  • json data was {a:b}, when I changed it to {"a":"b"} - the result.json() worked json 数据是 {a:b},当我将其更改为 {"a":"b"} 时 - result.json() 起作用了

For issue #2 the following is the code for getItems:对于问题 #2,以下是 getItems 的代码:

//app.data.service.ts
getItems(url:string) : Observable<Response> {
        return this._http.get(url)
            .map((response: Response) => {
                return response;     
            }).catch(this.handleError);
};

//app.data.service.spec.ts
it('should return {a:b}', () => {

    let data: string;

    dataService.getItems("http://localhost:8090/data/config.json")
           .subscribe(
            (response) => {
                //Here you can map the response to a type
                console.log("test getItems returned");
                data = JSON.stringify(response.json());
                console.log("data = " + data);
            },
            (err) => {
                //Here you can catch the error
                console.log("test getItems returned err");
            }
        );
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 bluebird - 函数返回promise对象而不是实际数据 - bluebird - function returns promise objects instead of actual data Promise 返回已履行的承诺,而不仅仅是数据 - Promise returns fulfilled promise instead of just the data Promise返回一个对象,而不是实际的字符串值[带有Firebase的Javascript] - Promise returns an object instead of the actual string value [Javascript w/ Firebase] 角异步函数返回undefined而不是promise - Angular async function returns undefined instead of promise 返回承诺的 Angular Http 请求中的链映射或链过滤器如何 - How Chain Map or Chain Filter inside of Angular Http request that returns a promise 函数返回已解决的承诺而不是数据 - Function returns resolved promise instead of data AngularJS Ajax http Promise返回其他数据 - AngularJS ajax http promise returns additional data 异步 Promise 返回未定义或区域感知 promise - Async Promise returns undefined or zone aware promise AngularJS:$ routeProvider解析$ http时返回响应obj而不是我的obj - AngularJS: $routeProvider when resolve $http returns response obj instead of my obj 角度js-返回promise代替数据对象 - angular js - Return promise instead data object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM