简单且常见的 Angular2+ 数据服务,处理错误并使用 Promises:
// imports skipped
class DataType {}
class Error {
constructor(error: HttpResponse) {
this.error = error.json()
}
}
@Injectable()
export class MyService<DataType> {
apiUrl = 'my/url';
constructor(protected http) {}
get(): Promise<DataType[] | Error> {
return this.http
.get(this.apiUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
protected handleError(error: HttpResponse): Promise<Error> {
console.error('An error occurred', error);
return Promise.reject(new Error(error));
}
}
Run Code Online (Sandbox Code Playgroud)
在此类中,get方法返回一个 Promise,它用数组解析DataType[],并用Error类型拒绝。
编译此代码,我收到此错误:
输入“错误| DataType[]' 不可分配给类型“DataType”。类型“Error”不可分配给类型“DataType”。
我正在使用 TypeScript 版本 2.4.2。我确信这种情况是在 TypeScript 升级之后开始发生的,这使得类型检查更加严格。
我想知道如何处理最新 TypeScript …
typescript angular-services angular-promise typescript-generics typescript2.0
在 Angular 2 中,我在以下位置定义了路由app.module.ts:
const appRoutes: Routes = [
{
path: '',
component: HomeComponent,
},
{
path: 'admin',
component: AdminComponent,
}
];
Run Code Online (Sandbox Code Playgroud)
我还有一个app.component显示菜单和搜索表单的。它app.component连接到一个服务 ( events.service.ts),该服务返回一个数组events。当提交搜索表单时,app.component调用服务来过滤事件,然后抓取它们:
getEvents(): void {
this.eventsService.getEvents().then(events => {this.events = events});
}
onSubmit() {
this.searchTerm = this.model.searchTerm;
this.eventsService.search(this.searchTerm).then(res => this.getEvents());
}
Run Code Online (Sandbox Code Playgroud)
我希望能够this.events从向下传递到(和)app.component中指定的两条路线。app.modulehomeadmin
我home.component.ts需要相同的events.service.ts,并在函数中从中获取事件onNgInit,但是当服务中的事件已通过 中的搜索进行更新时app.component.ts,在 的 初始化中获取的事件home.component.ts已过期。我希望它们能够同步。
对 Angular 服务的生命周期有一些疑问。我目前的理解是,如果你将服务注入到一个组件中,并且该服务是在该组件的providers数组中提供的,那么当该组件被销毁时,该服务也会被销毁。
这是一个不太抽象的例子:
@Component({
selector: 'app-offline-header',
templateUrl: './offline-header.component.html',
styleUrls: ['./offline-header.component.css'],
providers: [WebsocketService]
})
export class OfflineHeaderComponent{
constructor(private socket: WebsocketService) {}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,是WebsocketService在此组件的级别上注入的,而不是在 app.module(或其他模块)上注入的。那么如果这个组件被销毁,服务实例也会被销毁吗?
问题:
当这个组件被销毁时,WebsocketService实例是否也被销毁?
如果我们在根模块()中提供此服务app.module,那么服务是单例吗?如果是这种情况并且服务是单例,那么这个单例是何时创建的?
dependency-injection angular-services angular-module angular
我有 AngularJS 应用程序,我正在尝试制作混合应用程序,但无法使用 AngularJS 服务洞察 Angular 组件:出现错误
ERROR 错误:尝试在设置之前获取 AngularJS 注入器。
我的 main.ts 是
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
Run Code Online (Sandbox Code Playgroud)
应用程序模块:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, InjectionToken } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UpgradeModule, downgradeComponent } from '@angular/upgrade/static';
import { AppComponent } from './app.component';
import { SignInComponent } from "./modules/login/components/sign-in/sign-in.component";
import { authServiceProvider } from './shared/angularJS-upgraded-providers';
@NgModule({
declarations: …Run Code Online (Sandbox Code Playgroud) 我有一个 Angular 5 应用程序,我正在尝试使用 Google OAuth 登录来获取用户名,然后在服务中设置该用户名以用作登录用户。在添加登录名之前,我在服务中手动设置了该值,并且没有问题。现在我正在从 Google 登录设置用户名,看起来每次页面刷新(或调用服务的新实例时)我设置的值都会丢失。
该值从 Google 登录正确返回(我在控制台中检查过),所以我知道那里一切正常。我对 Angular 服务的印象是它们在其他模块中保持不变?是不是每次我调用该服务时都会创建一个新的空“tempuser”变量?如果是这样,有什么办法可以解决这个问题,以便我可以在整个应用程序中保留该值,直到用户注销?
这是服务本身:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from "@angular/http";
@Injectable()
export class WmApiService {
//private _baseUrl = "http://wm-api.webdevelopwolf.com/"; // Test server api
private _baseUrl = "http://localhost:58061/"; // Dev server api
tempuser = "";
tempuseravatar = "";
tempuserfullname = "";
tempuseremail = "";
userloggedin = 0;
modules: any;
constructor(private _http: Http) {
console.log('Wavemaker API Initialized...');
}
// On successful API call …Run Code Online (Sandbox Code Playgroud) 我有一个升级到 angular 9 的 angular 应用程序,我在其中使用了 angular 元素,它也升级到了 angular 9。我有一个服务模块(angular 9),我正在我的 angular 应用程序中导入它。我的 angular 元素也导入了相同的服务。我希望在我的 angular 应用程序和 angular 元素之间共享该服务的单个实例。Angular 9 提供了新的服务注入选项,现在称为“平台”。根据角度文档https://next.angular.io/api/core/Injectable
'platform' :页面上所有应用程序共享的特殊单例平台注入器。
我将我的服务更改为从根注入到平台级别。但我仍然看到我的服务的两个实例,一个在我的应用程序中,另一个在 angular 元素中。
@Injectable({providedIn: '平台' })
如何在我的应用程序和 angular 元素之间共享我的服务的单个实例。
我有一个名为的组件,customers-list我在其中显示 API 中的所有客户:
客户列表.html
<div *ngFor="let customer of customers">
<p>{{customer.name}</p>
</div>
Run Code Online (Sandbox Code Playgroud)
客户列表.ts
import { Component Input} from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';
@Component({
selector: 'drt-customers-list',
templateUrl: './customers-list.component.html',
styleUrls: ['./customers-list.component.scss'],
})
export class CustomerListComponent {
public customers: ICustomer[] ;
constructor(public customersService: CustomersService,) {}
public async ngOnInit(): Promise<void> {
this.customers = await this.customersService.getCustomersList('');
}
}
Run Code Online (Sandbox Code Playgroud)
我有另一个名为 的组件add-customer,我将在其中添加新客户,如下所示:
public onaddCustomer(): void {
this.someCustomer = this.addCustomerForm.value;
this.customersService.addCustomer( this.someCustomer).subscribe(
() => { // If …Run Code Online (Sandbox Code Playgroud) 是否有办法防止服务被注入到其原始模块之外?
假设我们正在projects.module.ts延迟加载并ProjectsModule导入ProjectsStoreModule. 我定义了一个服务ProjectsStoreModule,我不想将其注入到 中ProjectsModule,但可以将其注入到 中的任何位置ProjectsStoreModule。我想知道是否有办法实现这一目标?
注意: ProjectsStoreModule没有任何组件,因此我无法向组件提供服务。我想要隔离的服务将被注入到 Ngrx Effect 中,这是一个服务。
我做了什么:
我注册了ProjectsService:
@Injectable({
providedIn: ProjectsStoreModule
})
export class ProjectsService {
...
}
Run Code Online (Sandbox Code Playgroud)
项目模块:
@NgModule({
...
})
export class ProjectsModule {
...
imports: [ProjectsStoreModule]
}
Run Code Online (Sandbox Code Playgroud)
这种做法显然引起了如此多的Circular dependency警告。
ProjectsService然后我尝试在装饰器中注册@NgModule:
@NgModule({
...
providers: [ProjectsService]
})
export class ProjectsStoreModule {
...
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,通过将 导入ProjectsStoreModule到 中ProjectsModule,我想要成为内部服务的服务将在 中可用ProjectsModule。
任何帮助将不胜感激。
dependency-injection lazy-loading angular-services angular-module angular
我正在尝试从组件内的延迟加载模块访问服务实例。该模块没有任何可用于基于构造函数的注入的组件。Angular 文档没有帮助,我在 Medium 和类似网站上找到的所有各种教程都不适用。
以下是执行服务延迟加载的组件的代码。
await import ('./lazy.module')
.then(module => module.LazyModule)
.then(module => {return module;})
.then(module => this.compiler.compileModuleAsync(module))
.then(factory => {
let module = factory.create(this.injector);
this.lazyService = module.injector.get(LazyService);
});
Run Code Online (Sandbox Code Playgroud)
问题在于,在当前组件中包含 LazyService 将无法达到延迟加载的目的,并且 get() 方法似乎需要一个类型,这种方法只会产生先有鸡还是先有蛋的问题。我将 InjectionToken 作为另一种选择,但它需要一个通用定义,再次需要导入 LazyService。
谁能解释一下延迟服务加载应该如何完成?
我正在开发一个项目,遇到一个没有 @Injectable() 装饰器的服务,并且工作正常。到目前为止,我的印象是,在 Angular 中,如果我们想实现 DI,我们必须使用 @injectable() 装饰器并使用提供程序对其进行配置。使用提供者配置服务是强制性的,但使用 @injectable() 装饰器似乎不是强制性的。它仅在某些服务中使用。我注意到使用装饰器的服务和不使用装饰器的服务的唯一区别是前者本身有一些依赖项,而后者没有
我有两种类型的服务:
类型1:
export class SharedService {
//do something
}
Run Code Online (Sandbox Code Playgroud)
类型2:
@Injectable()
export class MainCreditService {
constructor(private http: Http, private config: Config) {
this.config.EndPoints.subscribe(endpointObj => {
this.environment = endpointObj;
});
}
Run Code Online (Sandbox Code Playgroud)
应用程序模块.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule} from '@angular/common/http'
@NgModule({
declarations: [
AppComponent, …Run Code Online (Sandbox Code Playgroud) angular-services ×10
angular ×9
lazy-loading ×2
typescript ×2
angular6 ×1
angular9 ×1
angularjs ×1
decorator ×1
google-oauth ×1
javascript ×1