Javascript 迭代对象数组角度2分量

Javascript 迭代对象数组角度2分量,javascript,angular,Javascript,Angular,有人能帮我吗?我做的不对,有什么遗漏吗? 我对--“this.ack.length”没有定义 this._activeChannelService.requestChannelChange(this.selectedchannel.channelName) .subscribe( ack => { this.ack= ack; console.log(" test: ", this.

有人能帮我吗?我做的不对,有什么遗漏吗? 我对--“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(名称:字符串):可观察{
警报(“在servicerequestChannelChange中”);
let headers=新的头({'Content-Type':'application/json'});
let options=newrequestoptions({headers:headers});
让postchannelname=“channelName=”+name;
let request t=新IRequest(名称);
log(JSON.stringify(requestt));
返回此。_http.post(此。_activateChangeUrl,JSON.stringify(requestt),{headers:headers})
//.map(此.extractData)
.map((res:Response)=>res.json()作为Iack[])
.do(data=>console.log(“All:+JSON.stringify(data)))
.接住(这个.把手错误);
}

在此处输入代码
在执行此操作之前执行。确认=确认被执行

这是一个函数

        ack  => {
            this.ack= ack;
            console.log(" test:  ", this.ack.length);
        }
您传递给subscribe(…),当数据到达时,可观察对象会调用它,这在调用服务器时可能需要很长时间


在此处输入代码
将立即执行。

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


因此,在订阅中进行秒服务呼叫。

您可以在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 });
    }

}
从'@angular/core'导入{Injectable};
从“/IPost”导入{IPost};
从'@angular/Http'导入{Http,Response,RequestOptions,Headers};
从“rxjs/Observable”导入{Observable};
导入'rxjs/add/operator/map';
导入'rxjs/add/operator/do';
导入“rxjs/add/operator/catch”;
@可注射()
出口邮递服务{
私有的_webApiBaseUrl=”http://localhost:62806/v1/Posts"
私有http:http;
构造函数(http:http){
这是http=http;
}   
getAll():可观察{
返回此。\u http.get(this.\u webApiBaseUrl+'/all',this.getHeaders())
.map((response:response)=>response.json())
.do(data=>console.log(`All data:\n${JSON.stringify(data)}`)
.接住(这个.把手错误);
    }   
私有句柄错误(错误:响应){
控制台错误(error);
返回Observable.throw(error.json().error | |'Server error');
}    
私有getHeaders()
{
let headers=新的headers();
headers.append(“授权”,“授权”);
headers.append(“内容类型”、“应用程序/json”);
返回新的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 
      );

  }

}
从'@angular/core'导入{Component,OnInit};
从“/IPost”导入{IPost};
从“/posts.service”导入{PostServices};
@组成部分({
选择器:“应用程序帖子”,
templateUrl:'./posts.component.html',
样式URL:['./posts.component.css']
})
导出类PostsComponent实现OnInit{
职位:IPost[];
错误消息:字符串;
私人邮政服务:邮政服务;
建造商(邮政服务:邮政服务){
这._postService=postService;
}
恩戈尼尼特(){
这是。_postService.getAll()
.订阅(
data=>{this.posts=data;console.log(“data.length:+data.length)},//此处
error=>this.errorMessage=错误
);
}
}

你能给我们提供
\u activeChannelService
的内容吗?echonax-我刚刚更新了请求以提供确认。-Matej Maloča-我已经更新了提供服务的内容,我可以看到请求正在到来并打印在控制台上控制台上打印的JSON全部为:{“结果”:“频道更改”,“消息”:“错误”}感谢您的帮助。从服务中获取ack值后,我有什么方法可以读取它吗?我看到您可以从回调中读取它,您可以从视图中绑定到它(Angular会在值可用时更新绑定,您可以使用
ack?.someProp
,以避免值不可用时出现异常
)您可以使用
.map(…)`而不是
.subscribe(…)
,然后使用
this.getChannel().subscribe(…)
,并在传递给subscribe的回调中访问它(假设
getChannel
)是包含
this的方法的名称。\u activeChannelService.requestChannelChange(…)
-这需要加前缀
return
to work)能否请您提供回调示例。这也与使用.map而不是.subscribe相矛盾?然后再打过来,订阅。感谢你的帮助?谢谢你的帮助居恩特·泽克鲍尔-现在一切都好了-谢谢
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 
      );

  }

}