【问题标题】:Iterate through an array of objects Angular 2 component遍历对象数组Angular 2组件
【发布时间】:2016-12-21 14:01:31
【问题描述】:

任何人都可以帮助我做错了什么,缺少什么吗? 我越来越不确定 --'this.ack.length'

this._activeChannelService.requestChannelChange(this.selectedchannel.channelName)
        .subscribe(
            ack  => {
                this.ack= ack;
                console.log(" test:  ", this.ack.length);
            },
            err => {
            console.log(err);
        });enter code here

确认时间到了 ack:Iack[];

Iack 有两个字符串类型的字段。结果和消息 我需要遍历 Iack[] 数组以获取结果和消息 如果 message=success 然后调用另一个服务

服务

requestChannelChange (name: string): Observable<Iack[]> {
    alert('in servicerequestChannelChange');
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    let postchannelname = "channelName=" + name;
    let requestt = new IRequest(name);
    console.log(JSON.stringify(requestt));
    return this._http.post(this._activateChangeUrl, JSON.stringify(requestt),{ headers: headers })
     //.map(this.extractData)
        .map((res:Response) => res.json() as Iack[])
        .do(data => console.log("All: " + JSON.stringify(data)))
     .catch(this.handleError);
}

【问题讨论】:

  • 可以提供_activeChannelService的内容吗?
  • echonax- 我刚刚更新了问题以提供确认。
  • – Matej Maloča - 我已更新以提供服务内容
  • 我可以看到 ask 即将到来并打印在控制台上
  • 控制台打印的 JSON 是 All: {"result":"Channel Change","message":"ERROR"}

标签: javascript angular


【解决方案1】:

你可以在你的 TS 服务中使用 observable:

import { Injectable } from '@angular/core';
import { IPost } from './IPost';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';


@Injectable()
export class PostServices {

    private _webApiBaseUrl = "http://localhost:62806/v1/Posts"
    private _http : Http;

    constructor(http : Http){
        this._http = http;
    }   

    getAll(): Observable<IPost[]> {
        return this._http.get(this._webApiBaseUrl + '/all', this.getHeaders())
        .map((response: Response) => response.json())
        .do(data => console.log(`All Data: \n ${ JSON.stringify(data) }`))
        .catch(this.handleError);
    }   

    private handleError(error: Response){
        console.error(error);
        return Observable.throw(error.json().error || 'Server Error');
    }    

    private getHeaders()
    {
        let headers = new Headers();
        headers.append("Authorization", ""); 
        headers.append("Content-Type", "application/json");
        return new RequestOptions({ headers: headers });
    }

}

在您的 TS 类中的用法:

import { Component, OnInit } from '@angular/core';
import { IPost } from './IPost';
import { PostServices } from './posts.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

  posts: IPost[];
  errorMessage: string;

  private _postService: PostServices;
  constructor(postService: PostServices) {
    this._postService = postService;
  }


  ngOnInit() {
    this._postService.getAll()
      .subscribe(
      data => {this.posts = data; console.log("data.length: " + data.length)}, // here
      error => this.errorMessage = <any>error 
      );

  }

}

【讨论】:

    【解决方案2】:

    enter code herethis.ack= ack; 执行之前执行

    这是一个函数

            ack  => {
                this.ack= ack;
                console.log(" test:  ", this.ack.length);
            }
    

    你传递给subscribe(...),当数据到达时,observable 调用它,当它调用服务器时可能需要很长时间。

    enter code here 立即执行。

    【讨论】:

    • 感谢您的帮助。有什么方法可以在服务结束后读取 ack 值?
    • 您可以从回调中读取它,您可以从视图绑定到它(Angular 会在值可用时更新绑定,您可以使用ack?.someProp 来避免值不存在时的异常然而可用) You can use .map(...)` 而不是.subscribe(...) 然后使用this.getChannel().subscribe(...) 并在您传递给订阅的回调中访问它(假设getChannel)是包含@的方法的名称987654332@ - 这需要以return 为前缀才能工作)
    • 能否提供回调示例。这也是矛盾的——使用 .map 而不是 .subscribe?然后回调.subscribe。感谢您的帮助?
    • 感谢您的帮助 Günter Zöchbauer- 现在一切正常- 谢谢
    【解决方案3】:

    您必须在服务订阅中检查是否成功。 observable 是一个异步调用,因此您要对该异步调用中的数据进行的任何调用都必须在其中进行,以保持安全调用。

    所以,在订阅中拨打您的第二次服务电话。

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 1970-01-01
      • 2020-01-18
      • 2017-11-20
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多