如何分离组件和服务?

时间:2017-03-22 12:36:06

标签: angular ionic-framework

我目前有一项功能允许我在我的应用上发布评论文章评论。 我想解除这个基于URLSearchParams的函数(我认为这是我不掌握的主要问题),将API部分放入我的服务并在当前组件中发布函数。 基本上我想在服务中使用我的URL + .map,其余部分在组件中。

submitReview(form) {
    let url = `http://mydomain/wp-json/wp/v2/users-reviews/reviews`;
    let params = new URLSearchParams;
    params.append('id', this.postId.toString());
    params.append('user_id', this.wp.getCurrentAuthorId().toString());
    params.append('name', 'Name');
    params.append('email', 'email@example.net');
    params.append('title', this.review.rating_title);
    params.append('description', this.review.rating_comment);
    params.append('rating', this.review.rating_score);
    console.log('sending request');
    return this.authHttp.post(url, params)
        .map(
            res => {
                let newReview = res.json();
                this.reviews.push(newReview);
                console.log(this.reviews);
                return newReview;
            }
        )
        .subscribe(
                data => {
                    this.statusMessage = "Review added successfully!";
                    //clear form
                    form.reset();
                },
                error => {
                    console.log(error._body);
                    this.statusMessage = error._body;
                }
        );
}

有人会有一个想法或一个文档,所以我可以通过? 谢谢:))

3 个答案:

答案 0 :(得分:2)

您现在看到组件中包含所有代码,因此您需要创建一个服务。如果您的表单格式正确,我的意思是您可以在请求中提取所需的所有值,而不是使用this.postId,请使用form.postId

// necessary imports

@Injectable()
export class MyService {

  constructor(private http: Http) { }

  // add the correct parameters here
  submitData(form) {
    // append your parameters and make request:
    return this.http.post(url, params)
      .map(res => res.json())
  }   
}

然后在组件中进行订阅......

reviews: any[] = [];

constructor(private myService: MyService) { } 

submitReview(form) {
  this.myService.submitData(form)
    .subscribe(newReview => {
       this.reviews.push(newReview);
       this.statusMessage = "Review added successfully!";
       //clear form
       form.reset();
    });
}

答案 1 :(得分:1)

@Injectable()
export class ReviewService {
  submitReview(id,user_id , .. . //and so on) {
        let url = `http://mydomain/wp-json/wp/v2/users-reviews/reviews`;
        let params = new URLSearchParams;
        params.append('id', id);
        params.append('user_id', user_id);
        // ... more params 
        console.log('sending request');
        return this.authHttp.post(url, params)
            .map(
                res => {
                    let newReview = res.json();
                    this.reviews.push(newReview);
                    console.log(this.reviews);
                    return newReview;
                }
            );
    }
}


class YourComponent(){

    constructor(public reviewService:ReviewService){}

    onSubmit(){

        id =  this.postId.toString();
        user_id =  this.wp.getCurrentAuthorId().toString();
        //and so on ... 
       this.reviewService.submitReview(id,user_id , .... /and so on )
            .subscribe(
                    data => {
                        this.statusMessage = "Review added successfully!";
                        //clear form
                        form.reset();
                    },
                    error => {
                        console.log(error._body);
                        this.statusMessage = error._body;
                    }
            );
    }

}

答案 2 :(得分:1)

你可以这样做:

在服务中

        @injectable
        export class ServiceName {
        submitReview(params): Observable<type> {
        let url = `http://mydomain/wp-json/wp/v2/users-reviews/reviews`;
         return this.authHttp.post(url, params)
                .map(
                    res => {
                        let newReview = res.json();
                        this.reviews.push(newReview);
                        console.log(this.reviews);
                        return newReview;
                    }
                );                    
    }
}

在组件中:

import { ServiceName} from './servicefile'
export class ComponentName(){    
    constructor(private serviceName : ServiceName){ }    
    onSubmit(){    
        //param code... 
       this.serviceName.submitReview(params)
            .subscribe({
                        // success code
                    },
                    error => {
                             // error handling
                    }
            );
    }
}