2017-10-06 4 views
0

양방향 서비스가 작동하도록 노력하고 있으며 단계가 누락되어 있거나 잘못 처리 한 부분을 파악할 수 없습니다. 콘솔에 오류가 없습니다. 내가 그것을 통해 데이터를 전송하려고 할 때, 아직 아무 반응이 없습니다. (Here's를) 내가 지금까지 무슨에 plunker을.양방향 서비스가 각도 2로 데이터를 업데이트하지 않음

내가 달성하기 위해 노력하고있어 과정이

로드와 같은 데이터의 본문에 간다 app.ts으로 반복하고 input.copmonent.ts으로 반복하십시오. (완료되었습니다).

{ 
    "questions":[ 
     { 
     "question": "How tall are you?", 
     "name": "height", 
     "id": "heightCtrl", 
     "template": "smInput" 
     }, 
     { 
     "question": "What is your favorite color?", 
     "name": "color", 
     "id": "colorCtrl", 
     "template": "smInput" 
     }, 
     { 
     "question": "What kind of car do you drive?", 
     "name": "car", 
     "id": "carCtrl", 
     "template": "smInput" 
     } 

    ] 
} 

데이터를 새 변수에로드하고 템플릿에 ngModel을 사용하여 사용자 응답을 업데이트하십시오.

//Input Component (omitted for relevance) 

@Component({ 
    template:` 
      <ng-container *ngIf="Qdata.template == 'smInput'"> 


       <p>{{Qdata.question}}</p> 

       <input type="text" 
        id="Qdata.id" 
        name="Qdata.name" 
        [(ngModel)]="Response.response" 
       > 


      </ng-container> 
      ` 
}) 

export class InputComponent implements OnInit{  

    @Input() Qdata: any;  //from app.ts 

    Response: FormResponse={}; // new variable 

    ngOnInit(){ this.prepResponse(); } 

    prepResponse(){ 
     let a = this.Qdata; 
     let b = this.Response; 

     b.question = a.question; 
     b.id = a.id; 
     b.name = a.name; 
    } 
} 



// Note: FormResponse is a custom class I made that's shaped the same as 
// the json data with the addition of a "response:string='';" field. 

input.component.tsResponse 변수에서 데이터를 수신하는 서비스를 만들고에 app.ts 가입하기를 사용할 수 있도록 (성공적으로 완료).

//Imports Observable and Subject from proper places 

@Injectable() 

export class AnswerService { 

    private FormList = new Subject<FormResponse[]>(); // so far I think this is contributing 
                 to the problem somehow. 

    addResponse(data:FormResponse){ 
    this.FormList.next(data); 
    } 

    getFormList(): Observable<FormResponse[]>{ 
    return this.FormList.asObservable(); 
    } 

} 

서비스에 addResponse() 기능으로 데이터를 전송하는 Input.component.ts에서 함수를 만듭니다 (대부분의 경우 ... 내 생각 .... 성공적으로 수행).

import { AnswerService } from './answer.service'; 

@Component({ 
    template:` 
     <ng-container *ngIf="Qdata.template == 'smInput'"> 
      <!--previous HTML --> 

      <button (click)="sendResponse()">send</button> 
      <!-- plan to ultimately use OnChanges, using this to test --> 

     </ng-container> 
     `, 
    providers: [AnswerService] 
}) 

export class InputComponent implements OnInit{  

    @Input() Qdata: any; 

    Response: FormResponse={}; 


    constructor(private _ans : AnswerService) {} 

    ngOnInit(){ ... } prepResponse(){...} 

    sendResponse(): void{ 
     let a = this.Response; 
     let grp = new FormResponse({ 
      question:a.question, 
      response:a.response, 
      id:a.id, 
      name:a.name 
     }); 

     this._ans.addResponse(grp); 
    } 

} 

app.tsFormList에 가입 만들기 (생각 .... 성공적으로 수행).

//app.ts (omitted for relevance) 

import { AnswerService } from './answer.service'; 

@Component({ 
    providers: [ AnswerService ] 
}) 

export class App implements OnInit{ 

    FormData: Array<FormResponse>=[]; 

    constructor(private _ans : AnswerService){} 

    ngOnInit(){ 
     this._ans.getFormList().subscribe(list => { list = this.FormData; }); 
    } 
} 

오류없이 벌금이 시점의 모든 하중에 도달 한 후 (성공적으로 완료),하지만 난 보낼 입력 필드에 뭔가를 입력하고 클릭하면, 아무것도 나는 app.ts 템플릿에서 만든 바인딩 쇼에서 보여줍니다 새로운 객체가 배열에 추가 될 때. push() 대신 next()과 같은 다른 방법을 시도하면 this.FormList.push() is not a function을 말하면서 오류가 발생합니다. 이 기능을 사용하려면 무엇을해야합니까?

또한 input.copmonent.ts 파일의 "데이터 복사 중"이라는 이유는 실제 사용시 Qdata 변수가 단지 4 가지 속성 이상일 것이기 때문에 지적하고 싶습니다. 그 4 개를 Response 변수에 보내 부모 구성 요소로 다시 보내야합니다. 나는이

<form #myForm="ngForm"> 

    <div *ngFor="let a of FormData"> 

     <div [attr.data-blank]="a.id" class="form-group"> 
     <!-- To force Angular to iterate a wrapper for each group --> 

      <input type="hidden" class="form-control" 
       [attr.name]="a.id" [(ngModel)]="a.question" 
      > 

      <input type="hidden" class="form-control" 
       [attr.name]="a.name" [(ngModel)]="a.response" 
      > 
     </div> 

    </div> 

</form> 

같은 숨겨진 프리 필드 입력 뭔가 나는이 방법이 있기 때문입니다 그것을 할 노력하고있어 그 이유와 템플릿 기반 양식을 반복하는 FormData 변수를 사용할 계획이 포인트 포워드에서

내가 작성한 설문지의 유형에는 여러 계층의 질문 내에 중첩 된 선택적 질문이 있습니다. which you can see here. 나는 이것이 사용자의 대답을 모으고 모든 두통없이 한 곳에 모으는 좋은 방법이되기를 바라고 있습니다. answer.serviceinput.component으로 가져 오는 한 사용자가 어떤 방향으로 가고 어떤 입력 상황이 필요 하든지 상관없이 항상 목록을 보내고 업데이트 할 수 있습니다. answer.service이이 용도로 제공 될 수 있도록하려면 어떻게해야합니까?당신의 child component도 공급자로 answer service하지 않다고 생각되는이 부모와 같은 서비스의 동일한 인스턴스를 얻는 대신 AnswerService의 새로운 인스턴스를 얻을 수 있도록

답변

1

여기에 몇 가지 문제가있다는 첫 번째 문제이다.

@Component({ 
    selector: 'input-component', 
    templateUrl: 'src/input.component.html' 
    // No providers 
}) 
export class InputComponent implements OnInit{ 

    // ... 

    /** Gets same instance of AnswerService as the parent component */ 
    constructor(private _ans: AnswerService){} 

    sendResponse(): void{ 
    this._ans.addResponse(this.Response); 
    }  
} 

또한, 귀하의 FormList에 대한 getter은 정확 나는 official example에서와 같이이 방법을 사용하는 것이 좋습니다.

서비스는 다음과 같아야합니다. 지금

당신의 app.component 당신과 같이 이벤트에 가입해야합니다 가입에 나는 FormData 배열에 결과를 추가하고있어 것을

@Component({ 
    selector: 'my-app', 
    templateUrl:'src/app.html', 
    providers: [ QuestionService, AnswerService ] 
}) 
export class App implements OnInit{ 

    FormData: FormResponse[] = []; 

    // ... 

    answerSubscription = this._ans.FormList.subscribe(a => { 
    console.log('gets here '+JSON.stringify(a, null, '\t')) 
    this.FormData.push(a) 
    }) 

    // ... 
} 

참고. QuestionService 코드는 약간의 수정이 필요하지만 아이디어를 얻을 수 있습니다.

여기는 plunker입니다.

+1

예이 작품!. 단, 데이터가 객체와 함께 전달되지 않는 이유를 이해할 수 없습니다. – Optiq

+1

수정 된 문제는'sendResponse' 메서드에 있습니다. 응답을 업데이트 할 것입니다. 플 런커에는 작동하는 문제가 있습니다. –

+0

정말 감사드립니다. 이제 이것이 왜 작동하는지 이해하는 것입니다. – Optiq

관련 문제