任何人都可以帮助我做错了什么,有什么遗失吗? 我未定义 - '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是时候了 ACK:IACK [];
Iack有两个字符串类型的字段。结果和消息 我需要遍历Iack []数组来获取结果和消息 if 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);
}
答案 0 :(得分: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
);
}
}
答案 1 :(得分:0)
enter code here
在执行this.ack= ack;
之前执行
这是一个功能
ack => {
this.ack= ack;
console.log(" test: ", this.ack.length);
}
你传递给subscribe(...)
并且当数据到达时,observable会调用它,这可能需要花费很长时间来调用服务器。
enter code here
会立即执行。
答案 2 :(得分:0)
您必须在服务订阅中检查是否成功。可观察的是异步调用,因此必须在其中进行关于该异步调用中的数据的任何调用以保持安全调用。
因此,请在订阅中进行秒服务。