订阅 Angular 2

编程入门 行业动态 更新时间:2024-10-26 21:34:06
本文介绍了订阅 Angular 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我希望我的 ngOnInit 函数执行以下操作:- 使用 this.structureRequest.sendRequest() 对一些数据进行 http 请求,它工作正常,在收到数据后使用 this.viewNodes() 函数开始查看它.我使用 subscribe ,但它不起作用,我想我在 subscribe 功能上做错了.请帮忙:)

I want my ngOnInit function do next things: - make http request for some data using this.structureRequest.sendRequest(),which works fine, and after data have been received to start view it using this.viewNodes() function. I use subscribe , but it does not work, I think I do something wrong with subscribe function. please help:)

HomeComponent.ts

HomeComponent.ts

import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {StructureRequestService} from './StructureRequestService';


export class Content {


ok: boolean;
content = [];
}
@Component({
providers: [StructureRequestService],
styleUrls: ['app/home/home.css'],
templateUrl:'./app/home/homePageTemplate.html'

})

export class HomeComponent {
contentArray = [];
myRes: Content;
showAssigned:boolean = false;
showSubitems:boolean = false;
showUsers:boolean = false;

constructor(private structureRequest: StructureRequestService) {}

ngOnInit() {
this.structureRequest.sendRequest().subscribe( this.viewNodes());

}

viewNodes() {
this.myRes = this.structureRequest.result;
this.contentArray = this.myRes.content;
this.showAssigned = true;
 }
 }

2.这里是http服务,http获取工作正常,接收到所有数据:

2.Here is http service, http get works fine, all data received:

import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';

import {Observable} from 'rxjs/Observable';

@Injectable ()
export class StructureRequestService {
result: Object;
//private myUrl = 'http://manny.herokuapp/audit/get/structure';
private myUrl = './app/home/nodes.json';  // local URL to structure APi
constructor (private http: Http) {
    //use XHR object
    let _build = (<any> http)._backend._browserXHR.build;
    (<any> http)._backend._browserXHR.build = () => {
        let _xhr =  _build();
        _xhr.withCredentials = true;
        return _xhr;
    };
}

sendRequest() {
    let body = JSON.stringify({});
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({
        headers: headers
    });
     this.http.get(this.myUrl, options)
        .map((res: Response) => res.json())
        .subscribe(res => {this.result = res;
            return this.result; });
}
}

3.so的问题是同步步骤:接收数据,而不是查看数据.

3.so the problem is to make synchronous steps: receive data, than view it.

推荐答案

你可能希望在请求返回值时执行 this.viewNodes 而不是执行 this.viewNodes 的结果()

You probably want to execute this.viewNodes when the request returns a value and not execute the result of this.viewNodes()

这个

this.structureRequest.sendRequest().subscribe( this.viewNodes());

应该改为

this.structureRequest.sendRequest().subscribe(() => this.viewNodes());

前者执行this.viewNodes()并将结果传递给subscribe(),后者创建一个新的内联函数传递给subscribe().这个内联函数在调用时执行 this.viewNodes()

The former executs this.viewNodes() and passes the result to subscribe(), the later creates a new inline function which is passed to subscribe(). This inline function, when called, executes this.viewNodes()

如果你想传递值 sendRequest() 返回它应该是

If you want to pass the value sendRequest() returns it should be

this.structureRequest.sendRequest().subscribe((result) => this.viewNodes(result));

更新

sendReqeust() 不返回任何内容.

应该是

return this.http.get(this.myUrl, options) ...

但这仅适用于您在代码中使用它的方式,前提是它返回 Observable.

but this only works the way you use it in your code if it returns an Observable.

但最后的 subscribe() 返回一个 Subscription

but the subscribe() at the end returns a Subscription

 return this.http.get(this.myUrl, options)
    .map((res: Response) => res.json())
    .subscribe(res => {this.result = res;
        return this.result; });

因此应改为

 return this.http.get(this.myUrl, options)
    .map((res: Response) => res.json())
    .map(res => {
      this.result = res;
      return this.result; 
    });

 return this.http.get(this.myUrl, options)
    .map((res: Response) => res.json())
    .do(res => {
      this.result = res;
    });

区别在于 do() 不会修改流的值,也不需要返回任何内容..map() 返回的值将被转发.如果要使用它,请确保导入 do(如 map).

The difference is that do() doesn't modify the value of the stream and doesn't need to return anything. The value returned from .map() will be forwarded. Ensure do is imported (like map) if you want to use it.

这篇关于订阅 Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 23:22:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1031290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!