我正在尝试为我正在处理的Angular 2项目创建打字稿定义,以便它可以成为可导出的库.
我有几个服务设置,将http请求返回到组件,所有这些都与以下内容非常类似:
public create(user:User) {
return this.http.post(this._apiUrls.create,
JSON.stringify(user), {
headers: this.apiConfig.getApiHeaders()
});
}
Run Code Online (Sandbox Code Playgroud)
然后我从一个组件调用这样的东西:
Session.create(user).subscribe((res:Response) => {
this.user = res.json().user
});
Run Code Online (Sandbox Code Playgroud)
这一切都正常,直到我在tsconfig文件中将'声明'变为true,以便我可以创建typescript定义文件.我的几个服务开始出现以下错误:
error TS4053: Return type of public method from exported class has or is using name 'Observable' from external module "node_modules/rxjs/Observable" but cannot be named.
Run Code Online (Sandbox Code Playgroud)
我大多理解这个问题,但我不知道解决方案.如果我将Observable导入服务,那么typescript linter将抛出错误,因为从技术上讲它没有在该文件中使用.
来自Angular 1这是我们在所有应用程序中采用的类似范例,以打破我们的代码,但也许我需要改变Angular 2中的方法?我已经看过很多其他的Angular 2示例,他们也以类似的方式完成了它.
我有一个使用服务的组件。该组件看起来像这样:
@Component({
moduleId: module.id,
selector: 'test',
providers: [HTTP_PROVIDERS, TestService]
})
export class TestComponent implements OnInit {
constructor(private _testService:TestService) {
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我HTTP_PROVIDERS在组件中添加了提供程序。之所以可行,是因为DI现在知道这些http类。但是,TestService真正使用Http该类的是我,而不是我的TestComponent。
@Injectable()
export class TestService {
constructor(private _http:Http) {
}
Run Code Online (Sandbox Code Playgroud)
我觉得由于这是使用Http类的服务,因此应该是包含提供程序本身的服务。在TestComponent不知道什么供应商TestService将需要。
由于服务类没有该组件装饰器,因此我不确定如何实际向其添加提供程序。如何向Service课程添加提供者?
我正在使用Karma处理Angular 2的单元测试用例,我遇到了一个函数,我在下面运行测试
expect(component.subscribeToEvents()).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)
我查看我的覆盖代码,测试文件中的行似乎没有覆盖订阅内的任何内容.我曾尝试使用MockBackend模拟服务函数内的api调用,但我不确定如何对订阅对象进行模拟,有人可以帮助我吗?
以下是test.component.ts
subscribeToEvents() {
this.subscription = this.czData.$selectedColorZone
.subscribe(items => {
this.resourceLoading = true;
if (!this.resourceData || (this.resourceData && this.resourceData.length === 0)) {
this.settings.layout.flypanel.display = false;
this.getAllResources(this.pagination.start, this.pagination.size);
}
else {
this.pagination.start = 1;
this.pagination.end = this.pagination.size;
this.getAllResources(1, this.pagination.size);
this.settings.layout.flypanel.display = true;
}
});
return true;
Run Code Online (Sandbox Code Playgroud)
}
unit-testing karma-jasmine karma-coverage angular2-services angular
我正在将我的应用程序迁移到最新的RC并且遇到一些我无法解决的错误.在决定问这里之前,我做了一个彻底的搜索,但没有任何运气.
因此,按下按钮时,应加载以下内容:
这是组件:
import { Component,OnInit } from '@angular/core';
import { HTTPService } from '../shared/api.service';
import { Server } from './server.model';
import { SharedService } from '../shared/moveData.service';
@Component({
templateUrl: './mainserverpage.template.html',
})
export class MainServerPage implements OnInit {
constructor(private _httpService: HTTPService,
private _moveData: SharedService) { }
errorMessage: string;
public servers: Server[];
isLoading = true;
tillLoading;
selectedServer: Server;
currentServer;
isServerOnline=false;
ngOnInit() {
this.getServers('qa');
}
reloadServers(env) {
this.servers = null;
this.getServers(env);
}
getServers(env?) {
this._httpService.getServers(env)
.subscribe(
value => {
this.servers = …Run Code Online (Sandbox Code Playgroud) 我需要一个全局模态开启服务,可以从任何模块创建动态组件.我有多个模块,每个模块都有模态组件.我简化了我的项目结构:
AppModule
---ModalOpenerService
--ModalTemplate
---AModule
---ModalComponent1
---ModalComponent2
---SimpleComponent
---BModule
---ModalComponent3
---ModalComponent4
Run Code Online (Sandbox Code Playgroud)
模态开启者服务有这样的方法:
@ViewChild('modalContainer', {read: ViewContainerRef}) modalContainer;
showModal(component: Type<any>,data?:any){
let componentFactory = this.resolver.resolveComponentFactory(component);
this.modalContainer.createComponent(componentFactory );
}
Run Code Online (Sandbox Code Playgroud)
我希望我的ModalOpenerService能够创建任何模态组件并显示它.但问题是模态组件属于不同的模块,模态开启器无法在其注入器的组件工厂列表中找到它们.
No component factory found for ModalComponent1. Did you add it to @NgModule.entryComponents
Run Code Online (Sandbox Code Playgroud)
显然,ModalComponent1不是AppModule的成员.
我可以通过将工厂方法作为参数而不是像下面这样的组件类型来打开模态:
//In SimpleComponent, I call my ModalOpenerService to open modal1. Because
//the simpleComponent's parent injector (AModule's injector) can find Modal1,
//this.resolver can resolve Modal1.
showModal1(){
this.modalOpenerService.showModal(this.resolver.resolveComponentFactory(ModalComponent1));
}
Run Code Online (Sandbox Code Playgroud)
在ModalOpenerService中
@ViewChild('modalContainer', {read: ViewContainerRef}) modalContainer;
showModal(factory:ComponentFactory<any>, data?:any){
this.modalContainer.createComponent(factory);
}
Run Code Online (Sandbox Code Playgroud)
因此,模块创建自己的组件,并且能够在其entryComponents …
我提供CookieXSRFStrategy了XSRFStrategy 在app.module.ts
providers: [
{ provide: APP_BASE_HREF, useValue: '/order/' },
{ provide: XSRFStrategy, useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken') },
{ provide: RequestOptions, useClass: DefaultRequestOptions }
],
Run Code Online (Sandbox Code Playgroud)
在第二次构建时使用watch/serve工作正常,但在使用--prod标志构建时,收到此错误:
ERROR in Error遇到静态解析符号值.不支持函数调用.考虑使用对导出函数的引用替换函数或lambda(原始.ts文件中的位置50:34),解析E中的符号AppModule:/repo/src/app/app.module.ts
ng --version
@angular/cli: 1.0.0
node: 6.9.1
os: win32 x64
@angular/common: 4.0.0
@angular/compiler: 4.0.0
@angular/core: 4.0.0
@angular/forms: 4.0.0
@angular/http: 4.0.0
@angular/platform-browser: 4.0.0
@angular/platform-browser-dynamic: 4.0.0
@angular/router: 4.0.0
@angular/animations: 4.0.0
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.0
Run Code Online (Sandbox Code Playgroud) 至少我以为我提供的正确.以下是我的app.module文件的相关片段以及我使用AuthHttp的服务.我按照自述文件中的配置创建了提供AuthHttp的工厂方法,但是在我的服务中无法识别它存在持续存在的问题.我已经阅读了有关嵌套依赖注入的文献,我觉得我正在做正确的事情.
app.module.ts
import { Http, RequestOptions } from '@angular/http';
import { provideAuth, AuthHttp, AuthConfig } from 'angular2-jwt/angular2-jwt';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig(), http, options);
}
@NgModule({
declarations: [
AppComponent,
ButtonFormComponent,
...
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule,
AppRoutingModule
],
providers: [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
},
Run Code Online (Sandbox Code Playgroud)
employee.service.ts
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import …Run Code Online (Sandbox Code Playgroud) 我尝试在HTTP.POST/GET请求中传递标头时出现以下错误 Argument of type '{header:Header;}' is not assignable to parameter of type 'RequestOptionsArgs'. Property 'null' is missing in the type '{header:Header;}'
我尝试了很多解决方案,但没有锁定它.
我的代码:
import { Injectable } from '@angular/core';
import { Response, RequestOptions, Headers, Http, URLSearchParams} from '@angular/http';
import { Observable, Subject } from 'rxjs/Rx';
import {Company} from './companyMaster';
import 'rxjs/add/operator/map';
import "rxjs/Rx";
import 'rxjs/add/operator/toPromise';
import {CommonService} from '../../common.service';
@Injectable()
export class CompanyMasterService {
private GetListActionUrl: string;
private AddEditActionUrl: string;
public headers = new Headers({ 'Content-Type': 'application/json' });
public options …Run Code Online (Sandbox Code Playgroud) 我有以下服务
@Injectable()
export class CollectionService<T> {
constructor(protected http: Http) {}
factory<T>(item?: any): T {
let type: new (item?: any) => T;
return new type(item);
}
item(id): Observable<T> {
return this.http.get(`${this.baseUrl}/${id}`)
.map((resp: Response)=> this.factory(resp.json()))
.catch((error: any) => {
return Observable.throw(error);
});
}
}
Run Code Online (Sandbox Code Playgroud)
编译成功通过,但我在浏览器控制台中有下列错误
TypeError: type is not a constructor
at PortalVideoService.webpackJsonp.../../../../../src/app/services/collection/collection.service.ts.CollectionService.factory (http://localhost:4200/main.bundle.js:1568:16)
at http://localhost:4200/main.bundle.js:1580:64
at Array.map (native)
at MapSubscriber.project (http://localhost:4200/main.bundle.js:1580:29)
at MapSubscriber.webpackJsonp.../../../../rxjs/operator/map.js.MapSubscriber._next (http://localhost:4200/vendor.bundle.js:24034:35)
at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (http://localhost:4200/vendor.bundle.js:13455:18)
at XMLHttpRequest.onLoad (http://localhost:4200/vendor.bundle.js:101703:38)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2838:31)
at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:93420:37)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2837:36)
Run Code Online (Sandbox Code Playgroud)
如何创建T类型的对象?
我想实现一个功能(在Angular2中),即登录后,如果用户保持浏览器空闲30分钟,则应在30分钟后返回时将其注销。这只能由前端完成。
我正在使用Angular 2.4版的angular CLI
如何在Angular2应用程序中实现此功能?
angular2-directives angular2-template angular2-services angular
angular ×9
typescript ×4
javascript ×2
angular2-jwt ×1
jwt ×1
node.js ×1
rxjs ×1
unit-testing ×1