简体   繁体   English

Angular2,如何在service.ts中使用JSON数据?

[英]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.

相关问题 Angular 8 如何在service.ts文件中使用动画过渡和触发器 - Angular 8 how to use Animations transitions and triggers in a service.ts file 如何更改service.ts angular中的变量值? - How to change variable value in service.ts angular? 如何在angular service.ts中传递fix变量? - How to pass fix variable in angular service.ts? 从角度为6的service.ts返回undefined - return undefined from service.ts in angular 6 将数据从service.ts传输到组件 - Transferring data from service.ts to component 如何绑定选择/选项值以在service.ts中而不是component.ts中获得请求功能(角度8) - How to bind selected/option value to get request function in service.ts and not component.ts (Angular 8) 如何在发射成功时处理从 service.ts 到 component.ts 的 socket.io 确认 Angular 8 - How to handle socket.io acknowledgement from service.ts to component.ts on emit success Angular 8 如何将 component.ts 中的变量发送到 service.ts 进行身份验证 Angular - How to send variable in component.ts to service.ts for authentication Angular 如何从 service.ts 文件中的 Component.ts 文件调用 function,该文件在 angular 的同一组件中 - How to Call function from Component.ts file in service.ts file which is in the same component in angular 如何将服务与来自Angular2的Json文件中的数据一起使用? - How to use a service with data from Json file, Angular2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM