我想在 订阅
中整合数组对象test.ts文件
export class AppComponent implements OnInit {
title = 'app works!';
observableBooks: Observable<Book[]>
books: Book[];
newarray: any[];
errorMessage: String;
constructor(private bookService: BookService) { }
ngOnInit(): void {
this.observableBooks = this.bookService.getBooksWithObservable();
this.observableBooks.subscribe(books => {
for (let entry of books) {
// push the value into db
}
let retrivedata: Array<number> = //retrive the db collection again
error => this.errorMessage = <any>error
});
}
}
test.html文件
<ul *ngFor="let book of retrivedata | async">
<li>{{book.price}}</li>
</ul>
我需要在HTML页面中迭代这个“arrayofObj”,这意味着有角度的模板页面
答案 0 :(得分:2)
试试这样:
export class AppComponent implements OnInit {
private retrivedata: Array<any> = [];
title = 'app works!';
observableBooks: Observable<Book[]>
books: Book[];
newarray: any[];
errorMessage: String;
constructor(private bookService: BookService) { }
ngOnInit(): void {
this.observableBooks = this.bookService.getBooksWithObservable();
this.observableBooks.subscribe(books => {
console.log('books', books);
this.retrivedata = books;
for (let entry of this.retrivedata) {
console.log('entry', entry)
}
}, (error) => {
this.errorMessage = <any>error
})
}
}
答案 1 :(得分:1)
您必须声明一个类变量来保存您在订阅“books”中获得的信息。
您无法在视图中使用let retrivedata: Array<number> = //retrive the db collection again
。您需要在类级别声明此变量。
看看:
export class AppComponent implements OnInit {
title = 'app works!';
retrivedata: Array<object> = []; // your view variable has to be created in a class level
observableBooks: Observable<Book[]>
books: Book[];
newarray: any[];
errorMessage: String;
constructor(private bookService: BookService) { }
ngOnInit(): void {
this.bookService.getBooksWithObservable().subscribe(books => {
books.forEach(entry => {
this.retrievedata.push(entry); //assign the data from subscription to your class variable
}
}
}
然后在你看来:
<ul *ngFor="let book of retrivedata"> // use your class variable in your view
<li>{{book.price}}</li>
</ul>
答案 2 :(得分:0)
更新:
我认为如果我们使代码更清洁一点,它应该看起来很接近:
app.component.ts:
export class AppComponent implements OnInit {
books: Book[];
errorMessage: string;
constructor(private bookService: BookService) { }
loadBooks() {
this.bookService.getBooksWithObservable().subscribe(
(res) => this.onSuccess(res.json),
(res) => this.onError(res.json)
);
}
ngOnInit() {
this.loadBooks();
}
private onSuccess(data) {
this.books = data;
}
private onError(error) {
this.errorMessage = error.toString();
}
}
HTML:
<div *ngFor="let book of books">
<span>{{book.price}}</span>
</div>
答案 3 :(得分:0)
如果你想迭代一个数组,但是你在subscribe
内,如果你使用forEach,那么你需要为this
添加forEach
参数来访问外部范围。
示例:强>
this.observableBooks.subscribe(
(books) => {
this.books = books;
//iterate over arrayofObj
books.forEach( (book) => {
//this will work
this.arrayofObj.push({fname: this.book.name});
}, this);
});
答案 4 :(得分:0)
plugman createpackagejson /Users/Admin/Desktop/testpluginswift/TestPluginSwift/