angular – 使用另一个自定义服务的服务时没有提供…错误
发布时间:2020-12-17 07:14:14 所属栏目:安全 来源:网络整理
导读:所以,我们谈论的是angular2,我知道它仍处于alpha状态. 我创建了一个我将在另一个服务中使用的基本服务.然后将后者用于组件中. 基本服务看起来像这样 import {Injectable,Observable} from 'angular2/core';import {Http} from 'angular2/http';import {Reque
所以,我们谈论的是angular2,我知道它仍处于alpha状态.
我创建了一个我将在另一个服务中使用的基本服务.然后将后者用于组件中. 基本服务看起来像这样 import {Injectable,Observable} from 'angular2/core'; import {Http} from 'angular2/http'; import {RequestOptionsArgs,Connection,ConnectionBackend} from 'angular2/http'; import {BaseRequestOptions,RequestOptions} from 'angular2/http'; import {RequestMethods} from 'angular2/http'; import {Response} from 'angular2/http'; import {Request} from 'angular2/http'; import {makeTypeError} from 'angular2/src/facade/exceptions'; @Injectable() export class MyOAuth extends Http { constructor(backend: ConnectionBackend,defaultOptions: RequestOptions) { super(backend,defaultOptions); } /** * Performs any type of http request. First argument is required,and can either be a url or * a {@link Request} instance. If the first argument is a url,an optional {@link RequestOptions} * object can be provided as the 2nd argument. The options object will be merged with the values * of {@link BaseRequestOptions} before performing the request. */ request(url: string | Request,options?: RequestOptionsArgs): Observable<Response> { var responSEObservable: any; if (isString(url)) { responSEObservable = httpRequest( this._backend,new Request(mergeOptions(this._defaultOptions,options,RequestMethods.Get,url))); } else if (url instanceof Request) { responSEObservable = httpRequest(this._backend,url); } else { throw makeTypeError('First argument must be a url string or Request instance.'); } return responSEObservable; } } 使用上述服务的其他服务看起来像这样(authenticate.js): import {Injectable,Inject} from 'angular2/angular2'; import {MyOAuth} from './MyOAuth'; @Injectable() export class AuthenticationService { constructor(@Inject(MyOAuth) http) { this.http = http; } authenticate(username,password,community) { console.log('authenticate'); } } 然后在课堂上使用这个服务我称之为: import {Page} from 'ionic/ionic'; import './login.scss'; import {AuthenticationService} from '../../services/authentication'; @Page({ templateUrl: 'app/login/login.html',providers: [AuthenticationService] //As of alpha 42 }) 我在浏览器中得到的错误是 EXCEPTION: No provider for MyOAuth! (LoginPage -> AuthenticationService -> MyOAuth) 对我来说,我必须导入MyOAuth … 解决方法
当您需要将自定义服务注入其他服务时,您需要在更大的上下文(组件,页面,应用程序)中提供服务
你可以做: import {Page} from 'ionic/ionic'; import './login.scss'; import {AuthenticationService} from '../../services/authentication'; @Page({ templateUrl: 'app/login/login.html',providers: [[AuthenticationService],[MyOAuth]] }) 对我来说,如果服务可以在多个地方重用,我总是在应用程序上下文中定义它.例如: @Component({ templateUrl: 'build/app.html',[MyOAuth]] }) class MyApp{ } 所以这些服务只会被安置一次.如果你提供它们,例如:Page1,Page2,它们将被实例化两次 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |