[英]Angular2, How to use JSON data in service.ts?
todo.service.ts 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 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);
});
}
}
I think, If i use " getDatas(){...getJSON...}
" I can get this data from "test_data.json" file. 我想,如果我使用“
getDatas(){...getJSON...}
”我可以从“test_data.json”文件中获取此数据。 and i think, i can put this data to " this.getDatas();
" 我想,我可以把这些数据放到“
this.getDatas();
”
But when i use " console.log("todos ================== " + todos)
" in todo.service.ts file, Result is "undefined". 但是当我在todo.service.ts文件中使用“
console.log("todos ================== " + todos)
”时,结果是“未定义”。
What's the problem? 有什么问题?
You can't switch back from async execution to sync execution. 您无法从异步执行切换回同步执行。
If you want to execute code after data from an async call arrived, you always have to chain the calls ( then
, map
, ...): 如果要在异步调用的数据到达后执行代码,则始终必须链接调用(
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;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.