백엔드에서 angular2 부트스트랩 방법으로 렌더링된 매개 변수를 전달하는 방법
백엔드에서 렌더링된 인수를 angular2 부트스트랩 메서드로 전달하는 방법이 있습니까?백엔드에서 제공된 값으로 BaseRequestOptions를 사용하여 모든 요청에 대해 http 헤더를 설정합니다.main.ts
파일은 다음과 같습니다.
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from "./app.component.ts";
bootstrap(AppComponent);
나는 이 인수를 루트 구성 요소(https://stackoverflow.com/a/35553650/3455681), 에 전달하는 방법을 찾았지만 해고할 때 필요합니다.bootstrap
생각 있어요?아이디어 있어요?
편집:
webpack.config.js 콘텐츠:
module.exports = {
entry: {
app: "./Scripts/app/main.ts"
},
output: {
filename: "./Scripts/build/[name].js"
},
resolve: {
extensions: ["", ".ts", ".js"]
},
module: {
loaders: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
}
};
업데이트 2
AoT 업데이트
AoT와 함께 작업하려면 공장 폐쇄를 제거해야 합니다.
function loadContext(context: ContextService) {
return () => context.load();
}
@NgModule({
...
providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: loadContext, deps: [ContextService], multi: true } ],
https://github.com/angular/angular/issues/11262 도 참조하십시오.
RC.6 및 2.0.0 최종 예제 업데이트
function configServiceFactory (config: ConfigService) {
return () => config.load();
}
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule,
routes,
FormsModule,
HttpModule],
providers: [AuthService,
Title,
appRoutingProviders,
ConfigService,
{ provide: APP_INITIALIZER,
useFactory: configServiceFactory
deps: [ConfigService],
multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
초기화가 완료될 때까지 기다릴 필요가 없는 경우 'class AppModule {}의 생성자도 사용할 수 있습니다.
class AppModule {
constructor(/*inject required dependencies */) {...}
}
힌트(종속성 포함)
예를 들어 라우터를 주입하면 순환 종속성이 발생할 수 있습니다.문제를 해결하기 위해 주입합니다.Injector
그리고 의존성을 얻습니다.
this.myDep = injector.get(MyDependency);
주사를 놓는 MyDependency
직접적으로 유사:
@Injectable()
export class ConfigService {
private router:Router;
constructor(/*private router:Router*/ injector:Injector) {
setTimeout(() => this.router = injector.get(Router));
}
}
갱신하다
에서도 동일하게 에 추가해야 .providers: [...]
트모의 대신 bootstrap(...)
(아직 테스트되지 않음).
갱신하다
전체적으로 Angular 내부에서 이 작업을 수행하는 흥미로운 접근 방식은 여기에 설명되어 있습니다. https://github.com/angular/angular/issues/9047#issuecomment-224075188
사용할 수 있습니다.
APP_INITIALIZER
이는 앱이 초기화될 때 함수를 실행하고 함수가 약속을 반환할 경우 제공하는 것을 지연시킵니다.이는 앱이 많은 지연 시간 없이 초기화될 수 있음을 의미하며 기존 서비스 및 프레임워크 기능도 사용할 수 있습니다.예를 들어, 사이트 정보가 제공되는 도메인 이름에 의존하는 멀티 테넌트 솔루션이 있다고 가정합니다.[http.com ] 전체 호스트입니다.letterpress.com 또는 전체 호스트 이름과 일치하는 사용자 지정 도메인.우리는 이것이 약속 뒤에 있다는 사실을 숨길 수 있습니다.
APP_INITIALIZER
.부트스트랩에서:
{provide: APP_INITIALIZER, useFactory: (sites:SitesService) => () => sites.load(), deps:[SitesService, HTTP_PROVIDERS], multi: true}),
sites.service.ts:
@Injectable() export class SitesService { public current:Site; constructor(private http:Http, private config:Config) { } load():Promise<Site> { var url:string; var pos = location.hostname.lastIndexOf(this.config.rootDomain); var url = (pos === -1) ? this.config.apiEndpoint + '/sites?host=' + location.hostname : this.config.apiEndpoint + '/sites/' + location.hostname.substr(0, pos); var promise = this.http.get(url).map(res => res.json()).toPromise(); promise.then(site => this.current = site); return promise; }
참고:
config
사용자 지정 구성 클래스일 뿐입니다.rootDomain
되요지일 입니다.'.letterpress.com'
이 예를 위해 그리고 다음과 같은 것들을 허용할 것입니다.aptaincodeman.letterpress.com
.이제 모든 구성 요소 및 기타 서비스가 가능합니다.
Site
그들에게 주입하고 사용합니다..current
앱 내의 어떤 약속도 기다릴 필요 없이 구체적으로 채워진 객체가 될 속성.이 접근 방식은 부트스트랩이 시작되기도 전에 큰 Angular 번들이 로드되고 다른 http 요청이 발생하기를 기다리는 경우에 상당히 눈에 띄는 시작 지연 시간을 단축하는 것처럼 보였습니다.
원래의
각도 종속성 주입을 사용하여 전달할 수 있습니다.
var headers = ... // get the headers from the server
bootstrap(AppComponent, [{provide: 'headers', useValue: headers})]);
class SomeComponentOrService {
constructor(@Inject('headers') private headers) {}
}
또는 준비된 상태로 제공합니다.BaseRequestOptions
과 같은
class MyRequestOptions extends BaseRequestOptions {
constructor (private headers) {
super();
}
}
var values = ... // get the headers from the server
var headers = new MyRequestOptions(values);
bootstrap(AppComponent, [{provide: BaseRequestOptions, useValue: headers})]);
Angular2 최종 릴리즈에서 APP_INITIALIZER 제공업체를 사용하여 원하는 것을 달성할 수 있습니다.
저는 완벽한 예를 들어 Gist를 썼습니다: https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9
주요 예는 JSON 파일에서 읽는 것이지만 REST 끝점에서 읽는 것으로 쉽게 변경할 수 있습니다.
필요한 것은 기본적으로 다음과 같습니다.
APP 설정_기존 모듈 파일의 INITIALIZER:
import { APP_INITIALIZER } from '@angular/core';
import { BackendRequestClass } from './backend.request';
import { HttpModule } from '@angular/http';
...
@NgModule({
imports: [
...
HttpModule
],
...
providers: [
...
...
BackendRequestClass,
{ provide: APP_INITIALIZER, useFactory: (config: BackendRequestClass) => () => config.load(), deps: [BackendRequestClass], multi: true }
],
...
});
이 행은 응용 프로그램을 시작하기 전에 BackendRequestClass 클래스에서 load() 메서드를 호출합니다.
내장된 라이브러리에서 angular2를 사용하여 백엔드로 http 호출을 하려면 "가져오기" 섹션에서 "HttpModule"을 설정해야 합니다.
클래스를 만들고 파일 이름을 "backend.request.ts"로 지정합니다.
import { Inject, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class BackendRequestClass {
private result: Object = null;
constructor(private http: Http) {
}
public getResult() {
return this.result;
}
public load() {
return new Promise((resolve, reject) => {
this.http.get('http://address/of/your/backend/endpoint').map( res => res.json() ).catch((error: any):any => {
reject(false);
return Observable.throw(error.json().error || 'Server error');
}).subscribe( (callResult) => {
this.result = callResult;
resolve(true);
});
});
}
}
백엔드 호출의 내용을 읽으려면 원하는 클래스에 BackendRequestClass를 삽입하고 getResult()를 호출하기만 하면 됩니다.예:
import { BackendRequestClass } from './backend.request';
export class AnyClass {
constructor(private backendRequest: BackendRequestClass) {
// note that BackendRequestClass is injected into a private property of AnyClass
}
anyMethod() {
this.backendRequest.getResult(); // This should return the data you want
}
}
이것으로 당신의 문제가 해결되는지 알려주세요.
엔트리 포인트에서 부트스트랩 자체를 호출하는 대신 다음과 같은 기능을 만들고 내보낼 수 있습니다.
export function doBootstrap(data: any) {
platformBrowserDynamic([{provide: Params, useValue: new Params(data)}])
.bootstrapModule(AppModule)
.catch(err => console.error(err));
}
설정(웹 팩/시스템)에 따라 글로벌 개체에 이 기능을 배치할 수도 있습니다.JS). 또한 AOT와 호환됩니다.
이는 부트스트랩을 지연시킬 수 있는 추가적인 이점이 있습니다.예를 들어 사용자가 양식을 작성한 후 이 사용자 데이터를 AJAX 호출로 검색하는 경우.이 데이터로 내보낸 부트스트랩 함수를 호출하기만 하면 됩니다.
이를 위한 유일한 방법은 공급자를 정의할 때 다음과 같은 값을 제공하는 것입니다.
bootstrap(AppComponent, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(/* parameters here */);
});
]);
그런 다음 이러한 매개 변수를 사용할 수 있습니다.CustomRequestOptions
명령어:
export class AppRequestOptions extends BaseRequestOptions {
constructor(parameters) {
this.parameters = parameters;
}
}
AJAX 요청에서 이러한 매개 변수를 가져오는 경우 다음과 같은 방법으로 비동기식으로 부트스트랩해야 합니다.
var appProviders = [ HTTP_PROVIDERS ]
var app = platform(BROWSER_PROVIDERS)
.application([BROWSER_APP_PROVIDERS, appProviders]);
var http = app.injector.get(Http);
http.get('http://.../some path').flatMap((parameters) => {
return app.bootstrap(appComponentType, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(/* parameters here */);
}})
]);
}).toPromise();
다음 질문을 참조하십시오.
편집
HTML에 데이터가 있으므로 다음을 사용할 수 있습니다.
함수를 가져와서 매개 변수와 함께 호출할 수 있습니다.
다음은 응용 프로그램을 부팅하는 기본 모듈의 샘플입니다.
import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';
export function main(params) {
bootstrap(AppComponent, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(params);
});
]);
}
그런 다음 HTML 기본 페이지에서 다음과 같이 가져올 수 있습니다.
<script>
var params = {"token": "@User.Token", "xxx": "@User.Yyy"};
System.import('app/main').then((module) => {
module.main(params);
});
</script>
이 질문: _layout.cshtml에서 Angular로 상수 값 전달을 참조하십시오.
언급URL : https://stackoverflow.com/questions/37611549/how-to-pass-parameters-rendered-from-backend-to-angular2-bootstrap-method
'programing' 카테고리의 다른 글
jQuery를 사용하여 클라이언트의 클립보드에 텍스트를 복사하는 방법은 무엇입니까? (0) | 2023.07.31 |
---|---|
Babel 6은 기본값을 내보내는 방법을 변경합니다. (0) | 2023.07.31 |
Oracle 인덱스의 크기를 어떻게 추정할 수 있습니까? (0) | 2023.07.31 |
바이트를 저장하기 위해 사용해야 하는 SQL Server 데이터 유형[] (0) | 2023.07.31 |
현재 디렉터리 및 모든 하위 디렉터리에 있는 DLL 파일의 파일 버전 및 어셈블리 버전 가져오기 (0) | 2023.07.31 |