todo.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class TodoService {
public todos
constructor(private http:Http) { }
getDatas(){
this.http.get('../json/test_data.json')
.map((res:Response) => res.json())
.subscribe(
data => {this.todos = data},
err => console.error(err),
() => console.log('done')
);
}
get(query = ''){
return new Promise(resolve => {
var data;
var todos = this.getDatas();
console.log("todos ================== " + todos)
if(query === 'completed' || query === 'active'){
var isCompleted = query === 'completed';
// data = todos.filter(todo => todo.isDone === isCompleted);
} else {
data = todos;
}
resolve(data);
});
}
}
todo.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css'],
providers: [TodoService]
})
export class TodoComponent implements OnInit {
private todos;
private activeTasks;
private newTodo;
private path;
constructor(private todoService: TodoService, private route: ActivatedRoute) { }
getTodos(query = ''){
return this.todoService.get(query).then(todos => {
this.todos = todos;
// this.activeTasks = this.todos.filter(todo => todo.isDone).length;
});
}
ngOnInit() {
this.route.params.subscribe(params => {
this.path = params['status'];
this.getTodos(this.path);
});
}
}
我想,如果我使用“getDatas(){...getJSON...}
”
我可以从“test_data.json”文件中获取此数据。
我想,我可以把这些数据放到“this.getDatas();
”
但是当我在todo.service.ts文件中使用“console.log("todos ================== " + todos)
”时,结果是“未定义的”。
有什么问题?
答案 0 :(得分:0)
您无法从异步执行切换回同步执行
如果您希望在来自异步呼叫的数据到达后执行代码,则始终必须将呼叫链接起来(then
,map
,...):
getDatas(){
return this.http.get('../json/test_data.json') // <<< return the observable
.map((res:Response) => res.json())
.map( // <<<=== instead of subscribe
data => {
this.todos = data; // <<< might not be necessary (done at caller site as well)
return data;
} //,
// err => console.error(err), // <<< use catch if you need to handle errors here
// () => console.log('done') // <<< use finally if you need to do something when the request is completed
);
}
get(query = ''){
// var data; // <<< redundant
return this.getDatas().map(todos =>
console.log("todos ================== " + todos)
if(query === 'completed' || query === 'active'){
var isCompleted = query === 'completed';
return data = todos.filter(todo => todo.isDone === isCompleted);
} else {
return todos;
}
});
}
getTodos(query = ''){
return this.todoService.get(query).subscribe(todos => {
this.todos = todos;
// this.activeTasks = this.todos.filter(todo => todo.isDone).length;
});
}