Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 服务类和定制类?_Angular_Typescript_Software Design - Fatal编程技术网

Angular 服务类和定制类?

Angular 服务类和定制类?,angular,typescript,software-design,Angular,Typescript,Software Design,我想知道创建服务的方法 我以JSON的形式从服务器注册表项[]获取数据 选择哪种方式来创建处理每个RegistryItem的服务或创建包含所有逻辑(如delete、edit)的类RegistryItem 或 换句话说,我应该将响应项包装到logic类还是更好地将逻辑移动到特定服务?最佳实践要求您将模型和业务逻辑分开。您的模型类型或接口应该只执行数据而不执行任何行为,您可以创建可注入的服务来操作您的模型: export interface RegistryItem { id: number;

我想知道创建服务的方法

我以JSON的形式从服务器注册表项[]获取数据

选择哪种方式来创建处理每个RegistryItem的服务或创建包含所有逻辑(如delete、edit)的类RegistryItem


换句话说,我应该将响应项包装到logic类还是更好地将逻辑移动到特定服务?

最佳实践要求您将模型和业务逻辑分开。您的模型类型或接口应该只执行数据而不执行任何行为,您可以创建可注入的服务来操作您的模型:

export interface RegistryItem {
 id: number;
 // other related properties
}
您的服务应该包含与操作RegistryItem相关的逻辑:

registry-item.component.html


我会选择单身服务。 因此,无论您将其注入应用程序的何处,您始终共享同一个服务实例,因此没有理由创建此服务的多个实例。 我们可以通过在可注射装饰器中以root或plaform形式提供它来实现这一点,请参见下面的示例:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from '../shared/employee';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class RestApiService {
  
  // Define API
  apiURL = 'http://localhost:3000';

  constructor(private http: HttpClient) { }

  /*========================================
    CRUD Methods for consuming RESTful API
  =========================================*/

  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }  

  // HttpClient API get() method => Fetch employees list
  getEmployees(): Observable<Employee> {
    return this.http.get<Employee>(this.apiURL + '/employees')
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // HttpClient API get() method => Fetch employee
  getEmployee(id): Observable<Employee> {
    return this.http.get<Employee>(this.apiURL + '/employees/' + id)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  // HttpClient API post() method => Create employee
  createEmployee(employee): Observable<Employee> {
    return this.http.post<Employee>(this.apiURL + '/employees', JSON.stringify(employee), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  // HttpClient API put() method => Update employee
  updateEmployee(id, employee): Observable<Employee> {
    return this.http.put<Employee>(this.apiURL + '/employees/' + id, JSON.stringify(employee), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // HttpClient API delete() method => Delete employee
  deleteEmployee(id){
    return this.http.delete<Employee>(this.apiURL + '/employees/' + id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // Error handling 
  handleError(error) {
     let errorMessage = '';
     if(error.error instanceof ErrorEvent) {
       // Get client-side error
       errorMessage = error.error.message;
     } else {
       // Get server-side error
       errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
     }
     return throwError(errorMessage);
  }

}
})

如果您的代码可能在一个运行多个Angular应用程序的网页上使用,您可能希望在平台中而不是在根目录中提供它。100%只使用一个服务实例

要实现这一点,只需将可注入装饰器从:

@Injectable({
  providedIn: 'root'
})
致:


您能否编辑该问题并添加发出http请求并向模型返回数据的RegistryHttpService?我试图查看类之间的所有关系,我是否应该将RegistryItem注入RegistryItemService?您不可以也不能将普通模型注入服务,为什么您会这样做?例如,只有服务是可注入的,用于准备响应数据!我不知道如何以及在何处创建MNAKE请求和返回数据的层。如何填充模型和存储?您可以通过服务getAll:RegistryItem[]中的方法公开它,并从组件调用它,然后将它们存储在其中。或者在您的单例服务中声明一个包含该数据的属性。我更新了answerYou,将业务逻辑与http逻辑和模型混合在一起。全部加在一起。但我想从http请求中分离出核心业务逻辑,并从请求中获得模型。我不确定您所说的模型是什么意思。模型用于实例化一个类,通常不止一次。我的全部答案基于这样一个事实,即这样一个服务/类只需实例化一次。这种服务不需要模型,因此逻辑和模型之间没有混合。我只是提供了一个简单的例子,大家都很容易理解,如果你要做复杂的计算或想分割东西。。。这取决于你。但这超出了你的问题范围。
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class RegistryItemService {
// your backend base api url
baseUrl = 'http://localhost:3000/api';
getAll() : Observable<RegistryItem[]> {
   return this.http.get<RegistryItem[]>(this.baseUrl+ '/registry-items')
}
update(item: RegistryItem) : Observable<RegistryItem> {...}
create(item: RegistryItem) : Observable<any> {...}
delete(id: number) : Observable<any> {...}
drawRegister() {...};
}
@Component({
  selector: 'app-registry-item',
  templateUrl: './registry-item.component.html',
})
export class RegistryItemComponent {
  registryItems: RegistryItem[] = [];
  constructor(private service: RegistryItemService ) { 
    this.service.getAll().subscribe(res=>  {
            this.registryItems = res;
           },
         err=> console.error(err)
      );
  }

}
<div>
  <h1>Registry items<h1/>
   <!-- 
     show your data in a list or table or whatever you like
    -->
   <ul>
    <li *ngFor="let i of registryItems"> 
      <span>{{i.id}} </span>
      <!-- show other info
       <span>{{i.name}} </span> -->
    </li>
   </ul>
</div>
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from '../shared/employee';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class RestApiService {
  
  // Define API
  apiURL = 'http://localhost:3000';

  constructor(private http: HttpClient) { }

  /*========================================
    CRUD Methods for consuming RESTful API
  =========================================*/

  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }  

  // HttpClient API get() method => Fetch employees list
  getEmployees(): Observable<Employee> {
    return this.http.get<Employee>(this.apiURL + '/employees')
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // HttpClient API get() method => Fetch employee
  getEmployee(id): Observable<Employee> {
    return this.http.get<Employee>(this.apiURL + '/employees/' + id)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  // HttpClient API post() method => Create employee
  createEmployee(employee): Observable<Employee> {
    return this.http.post<Employee>(this.apiURL + '/employees', JSON.stringify(employee), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  // HttpClient API put() method => Update employee
  updateEmployee(id, employee): Observable<Employee> {
    return this.http.put<Employee>(this.apiURL + '/employees/' + id, JSON.stringify(employee), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // HttpClient API delete() method => Delete employee
  deleteEmployee(id){
    return this.http.delete<Employee>(this.apiURL + '/employees/' + id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // Error handling 
  handleError(error) {
     let errorMessage = '';
     if(error.error instanceof ErrorEvent) {
       // Get client-side error
       errorMessage = error.error.message;
     } else {
       // Get server-side error
       errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
     }
     return throwError(errorMessage);
  }

}
export const environment = {
production: false,
API_URL: 'http:/blabla.com/blabla/api',
API_EMPLOYEE: 'http://test.api.com/test-api/api',
@Injectable({
  providedIn: 'root'
})
@Injectable({
  providedIn: 'platform'
})