2017-12-05 11 views
1

私は角4のアプリケーションをdjangoと統合しています。角4はちょうどdjangoテンプレートのいくつかのデータを表示するためのもので、私はdjangoでいくつかのRESTful APIを持っています。私はwebpackを使って.tsファイルをjsにコンパイルし、django templates.Iに含まれています良い。どのように私はdjangoテンプレートから角度4にデータを渡すことができますか?

私は私が角度成分で静的URL(すなわち正確なURL)を使用していたとき、私は角度のテンプレートを取得しています角度成分コードに

import { Component,OnInit } from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
@Component({selector: 'my-component', 
      template: '<ul> 
         <li *ngFor="let res in results"> 
         {{res}} 
         </li></ul>' 
}) 
export class MyComponent { 
results: {}; 
constructor(private http: Http) { 

} 
app_func(){ 
    this.http.get('http://someurl/id/test.json').subscribe(res => { 
     this.results = res.json(); 
    }) 
} 
ngOnInit(): void { 
this.app_func(); 
} 

とDjangoテンプレート

{% block bundles %} 
    {% render_bundle 'main' %} 
{% endblock bundles %} 

{% block breadcrumbs %} 
{{ block.super }} 
{% breadcrumb test.name 'detail' test.id %} 
{% endblock breadcrumbs %} 

{% block content %} 
<div class="row"> 
    <div class="col-md-12 col-md-offset-0"> 
    <div class="test" id="results"> 
     <my-component>Loading...<my-component> 
    </div> 
    </div> 
</div> 
{% endblock content %} 

を持っています。

しかし、動的URLがstaticではないので、私はdjangoビューの値である{{test.id}}値を角度成分に渡して、このidをURLに使用してjsonを取得する必要があります。何か案は??

+0

'this.http.get(使用してみてください 'にhttp:// someurl/$ {} test.id /test.json' ).subscribe(res => {'URL文字列にシングル頂点の代わりにバックティックを使う –

+0

それは私のためには機能しません。グローバル変数または関数に渡す必要があります – Vicky

答えて

1

角度コンポーネントファイルでは、メソッドをpublicとして作成し、jsファイルまたはhtmlのスクリプトタグで使用して、データまたは値を渡すことができます。コンパイル済みのjsバンドルがロードされた後に関数を呼び出します。

角度成分コード

import { Component,OnInit,NgZone,OnDestroy } from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
@Component({selector: 'my-component', 
     template: '<ul> 
        <li *ngFor="let res in results"> 
        {{res}} 
        </li></ul>' 
}) 
export class MyComponent { 
results: {}; 
constructor(private http: Http,private zone:NgZone) {} 
app_func(test_id){ 
this.zone.run(() => 
    this.http.get('http://someurl/'+test_id+'/test.json').subscribe(res => 
    { 
     this.results = res.json(); 
    }) 
); 
} 
ngOnInit(): void { 
(<any>window).app_func = this.app_func.bind(this); 
} 
ngOnDestroy() { 
(<any>window).app_func = null; 
} 

とDjangoテンプレート

{% block bundles %} 
{% render_bundle 'main' %} 
{% endblock bundles %} 

{% block breadcrumbs %} 
{{ block.super }} 
{% breadcrumb test.name 'detail' test.id %} 
{% endblock breadcrumbs %} 

{% block scripts %} 
<script> 
app_func(test_id='{{test.id}}'); 
</script> 
{% endblock scripts %} 

{% block content %} 
<div class="row"> 
<div class="col-md-12 col-md-offset-0"> 
<div class="test" id="results"> 
    <my-component>Loading...<my-component> 
</div> 
</div> 
</div> 
{% endblock content %} 
関連する問題