如何在Angular2中创建服务?

时间:2017-04-12 10:22:37

标签: angular odoo-9

我是angular2的初学者,我正在构建这个应用程序,我正在使用这段代码从Odoo数据库中获取一些数据,我只想在服务中实现它,因为应用程序正在增长,但我我不知道怎么做正确的方法,我不知道该返回什么:

这是app.component.ts:

import { Component, OnInit } from '@angular/core';
import { OdooRPCService } from 'angular2-odoo-jsonrpc';
import { Http} from '@angular/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [OdooRPCService]
})
export class AppComponent implements OnInit{

  projectList;
  ngOnInit(){
    let self =  this;
    self.projectList = [];
    self.odooRPC.init({
      odoo_server: "https://demo9"
    });
    self.odooRPC.login('DB', 'admin', 'admin').then(res => {
      console.log('login success');
    }).catch( err => {
      console.error('login failed', err);
    })
    self.odooRPC.call('project.project', 'search_read', [], {}).then((projects:any) => {
      if(projects){
        self.projectList = projects;
      }
    })
  }
  constructor( private odooRPC: OdooRPCService){
  }}

这里是projects.service.ts:

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import {ProjectList}from'./projects';
import { OdooRPCService } from 'angular2-odoo-jsonrpc';

@Injectable()


export class ProjectsService {
   public projectList;
  constructor(private projectsservice:ProjectsService, private http:Http, private odooRPC: OdooRPCService) {}

  getProjects(){

    let self =  this;
    self.projectList = [];
    self.odooRPC.init({
      odoo_server: "https://demo"
    });
    self.odooRPC.login('DB', 'admin', 'admin').then(res => {
      console.log('login success');
    }).catch( err => {
      console.error('login failed', err);
    })
    self.odooRPC.call('project.project', 'search_read', [], {}).then((projects:any) => {
      if(projects) {
        self.projectList = projects;
      })

     }
  }}

和模型projects.ts:

export interface ProjectList  {
    name:string;
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import {ProjectsService} from "./projects.service";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [ProjectsService],
  bootstrap: [AppComponent]
})
export class AppModule { }
谢谢。

1 个答案:

答案 0 :(得分:0)

你的构造函数

constructor(
  private projectsservice:ProjectsService,
  private http:Http,
  private odooRPC: OdooRPCService
) {}

你不能在ProjectsService中注入ProjectsService(它是自己的)。我没有在课堂上看到它的任何用法,那你为什么要注射呢?

请阅读ng2文档:here