我正在尝试从组件内的延迟加载模块访问服务实例。该模块没有任何可用于基于构造函数的注入的组件。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) 如果用户碰巧从任何其他路线刷新,那么将用户引导到主页的最佳方式是什么(如果你正在使用ui-router,就像我一样说明状态).
例如 - 我希望它们从inventory页面开始.如果他们想要进行编辑,他们会前往edits页面,但如果他们刷新该页面,他们会inventory再次直接进入该路径.
angularjs angularjs-directive angular-services angular-ui-router
通常我写SPA并在控制器之间共享数据对于服务来说很简单.
我没有使用SPA格式(不使用ng-view),并尝试在页面之间共享数据,但在加载第二页(获取数据)时为空.
PAGE1(index.html):
<div ng-controller="CreateList">
<input type="text" ng-model="myValue">
<div ng-click="share(myValue)">Share</div>
</div>
Run Code Online (Sandbox Code Playgroud)
第2页:
<div ng-controller="GeList">
<p>{{ sharedData }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
app.controller('CreateList', function($scope, $location, $http, serviceShareData) {
$scope.share= function (selectedValue) {
if (selectedValue === undefined ) {
console.log ("its undefined");
}
else {
console.log (selectedValue);
serviceShareData.addData(selectedValue);
window.location.href = "PAGE2.html";
}
}
});
app.controller('GeList', function($scope, $location, $http, serviceShareData) {
$scope.sharedData = serviceShareData.getData();
console.log($scope.sharedData);
});
app.service('serviceShareData', function() {
var myData = [];
var addData = function(newObj) {
myData.push(newObj);
}
var getData = function(){
return …Run Code Online (Sandbox Code Playgroud) 在我的Angular应用程序中,我有一个简单的通知工厂,它允许我存储和获取我想传达给用户的信息:
(function() {
'use strict';
angular
.module('peaches')
.factory('NotificationFactory', factory);
// factory.$inject = ['dependencies'];
/* @ngInject */
function factory() {
var messages = [];
var service = {
postAlert: postAlert,
getAlerts: getAlerts,
deleteAlert: deleteAlert
};
return service;
function postAlert(alert) {
messages.push(alert);
if (alert.duration) {
setTimeout(function() {
deleteAlert(alert);
}, alert.duration)
}
}
function getAlerts() {
return messages;
}
function deleteAlert(alert) {
messages.splice(messages.indexOf(alert), 1);
}
}
})();
Run Code Online (Sandbox Code Playgroud)
正如您在postAlert函数中看到的,我希望能够duration在duration毫秒数之后删除通知,如果所述通知具有属性.
目的是让某些类型的通知在几秒钟后自动消失,而不是要求交互关闭.
这是一个示例通知:
var reportSaved = {
msg: "Report saved.", …Run Code Online (Sandbox Code Playgroud) 我对Angular很新,并且已经停留了一段时间了.我正在尝试创建一个从内部webapi获取数据的服务,它之前有效,但现在它给出了一个我无法解决的错误.希望你们其中一个人可以帮助我......服务:
import {Injectable} from "@angular/core";
import {Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {GraphData} from './graph-data';
@Injectable
export class GraphDataService {
private dataApiUrl = 'app/graph-data';
constructor(private http: Http) {}
getGraphData() : Promise<GraphData[]> {
return this.http.get(this.dataApiUrl)
.toPromise()
.then(response => response.json().data as GraphData[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('an error occurred', error); // only for demo
return Promise.reject(error.message || error);
}
}
Run Code Online (Sandbox Code Playgroud)
编译为js时出错:
app/graph-data.service.ts(11,1): error TS1238: Unable to resolve signature of class decorator when called as an expression.
Supplied parameters do …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个处理Angular 2中的联系人的服务.这是我到目前为止所做的.
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ContactsService {
constructor(private http: Http) { }
addContact(contact): Promise<any> {
return this.http
.post('http://localhost:8000/contacts', contact)
.toPromise()
.then(response => response.json())
.catch(error => error.json());
}
}
Run Code Online (Sandbox Code Playgroud)
现在服务工作正常,如果我400+在响应上获得状态代码,代码就会catch凝视,如果200代码进入then状态并返回响应.
但是当我在一个组件中使用它时,then无论是否正常,它都会进入状态.
addingContact() {
this.contactsService
.addContact(this.user)
.then(
(contactx) => { console.log('THEN = ' + JSON.stringify(contactx)); },
(err) => { console.log('CATCH = ' + JSON.stringify(err)); }
);
}
Run Code Online (Sandbox Code Playgroud)
有什么我缺少的,我应该在服务上扔东西,所以代码进入错误开始,我得到一个 …
如何在不重新加载应用程序的情况下重新启动服务?
我不想用window.location.reload().
我想使用subject将数据发送到另一个组件(用于赚钱目的).我无法取回数据.这是我的代码:
app.component.ts
import { Component } from '@angular/core';
import { shareService } from './share.service';
@Component({
selector: 'my-app',
template: `
<hello></hello>
<button (click)="passData()">
Start
</button>
`,
styleUrls: [ './app.component.css' ],
providers:[shareService]
})
export class AppComponent {
constructor(private service : shareService){}
passData(){
this.service.send("hello");
}
}
Run Code Online (Sandbox Code Playgroud)
hello.component.ts
import { Component, Input } from '@angular/core';
import { shareService } from './share.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'hello',
template: `<h1>Hello!</h1>`,
styles: [`h1 { font-family: Lato; }`],
providers:[shareService]
})
export class HelloComponent { …Run Code Online (Sandbox Code Playgroud) 我有打字稿或javascript语法问题.谁能告诉我_ => this.log ...意味着什么?
我习惯于看到一个名称,参数被传递到那里的箭头函数.
它只是意味着"没有参数"吗?
参考:https://angular.io/tutorial/toh-pt6#add-heroserviceupdatehero
/** PUT: update the hero on the server */
updateHero (hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
);
}
Run Code Online (Sandbox Code Playgroud) angular-services ×10
angular ×5
angularjs ×5
javascript ×5
typescript ×2
decorator ×1
lazy-loading ×1